It is used to create or generate a child process. So, The purpose of fork() is to create a new process, which becomes the child process of the caller. It takes no arguments and returns a process ID.
fork() returns a zero to the newly created child process
fork() returns a positive value,to the parent process
If fork() returns a negative value, the creation of a child process was unsuccessful.
For example:
1)
int main()
{
fork();
printf("Hello!\n");
return 0;
}
Output:
Hello!
Hello!
2)
int main()
{
fork();
fork();
fork();
printf("hello\n");
return 0;
}
Output:
hello
hello
hello
hello
hello
hello
hello
hello
The number of times ‘hello’ is printed is equal to the number of processes created. Total Number of Processes = 2^n, where n is the number of fork system calls. So here n = 3, 2^3 = 8.So there are a total of eight processes (new child processes and one original process).
The total number of child processes created is 2^n-1. So, 2^3-1 is 7.
Happy Coding!
Follow us on Instagram @programmersdoor
Join us on Telegram @programmersdoor
Please write comments if you find any bug in the above code/algorithm, or find other ways to solve the same problem.
Follow Programmers Door for more.
Commentaires