fork() in C
Introduction
To create a new function in the system, there is a need for a system call, i.e. fork system call. It is also known as the child process. These child classes run concurrently with the parent process. Here parent process is fork call(). Both processes will follow the instruction of the fork() system call after the creation of the new child process. The newly created child process uses the criteria of the same pc(program counter), same CPU registers, and duplicate open files which operate in the parent process. It returns an integer value without using a parameter. The different values returned by fork() are as follows:
- When the creation of the child process is unsuccessful, then it returns a negative value.
- When the creation of the child process is successful, then it returns zero.
- When it returns a parent value, it produces a positive value.
What is a fork()?
In computer language, it is a method of creation of a process in an operating system like Linux and Unix. With the help of the function, we can copy a new child function from the parent process. When the parent process fails, then the child process also fails.
Example 1
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
fork();
printf("javaTpoint\n");
return 0;
}
Output:
javaTpoint
javaTpoint
Example 2
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
void for example()
{
if (fork() == 0)
printf("Hello, I am from Child!\n");
else
printf("Hello, I am from Parent!\n");
}
int main()
{
forkexample();
return 0;
}
Output:
Hello, I am from Parent!
Hello, I am from Child!
Example 3
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
printf("I am: %d\n", (int) getpid());
pid_t pid = fork();
printf("fork returned: %d\n", (int) pid);
if (pid < 0) {
perror("Fork failed");
}
if (pid == 0) {
printf("I am the child with pid %d\n", (int) getpid());
printf("Child process is exiting\n");
exit(0);
}
printf("I am the parent waiting for the child process to end\n");
wait(NULL);
printf("parent process is exiting\n");
return(0);
}
Output:
I am: 3363
fork returned: 3364
I am the parent waiting for the child process to end
fork returned: 0
I am the child with pid 3364
The child process is exiting
the parent process is exiting