The function fork has exactly the meaning it has on English dictionary.It is the point where something, a road or river divides into two parts. In programming the process divides into two parts thus creating a child process and parent process. The parent process is actually the process we are running.
Header File: <unistd.h>
Whenever we use fork() a child process is created. The working of fork can be understood by considering the following example:
#include <unistd.h>
int main ()
{
printf("Hello World\n");
fork();
printf("Goodbye Cruel World\n");
}
Output
Hello World
Goodbye Cruel World
Goodbye Cruel World
You can see that the line after which the function 'fork()' is called, is printed twice or rather the next statement after the function is executed twice. When the function is called it creates the copy of that function and name it as child and starts executing it (child) after the fork() function and then it returns to the parent function and continue its execution. The child process will be run in a separate memory space and any change made to variables in te child won't affect the parent variable.
Consider the following example:
Code
#include <stdio.h>
#include <unistd.h>
int main ()
{
int i=0;
printf("Hello World %d\n",i++);
fork();
printf("Goodbye Cruel World %d\n",i++);
}
Output
Hello World 0
Goodbye Cruel World 1
Goodbye Cruel World 1
Lets analyse the output:
Hello World 0 -PARENT
Goodbye Cruel World 1 -CHILD
Goodbye Cruel World 1 -PARENT
This order can change that is, this can also be the case: We execute the program, comes across fork(), complete execution of parent and then call the child to execute. The acually depends on the OS we cannot predict it.But we can do this thing: Execute program,comes across fork, ask parent to wait until child process get completed(click here to know more about wait()) ,now execute the remaining part of parent.
Identifying parent and child process
fork() will return a value 0 when it is called in child and will return pid of child when it is in parent process.If fork() fails then it returns -1 in parent process.(To know about PID click here) The following example illustrate the fact:
Code
#include <stdio.h>
#include <unistd.h>
int main ()
{
int pid;
printf("Hello World\n");
pid = fork();
if(pid==-1)
printf("\nError unable call fork");
else if(pid != 0)
printf("I'm the Father and my son's PID is %d\n",pid);
else
printf("I'm the Son\n");
printf("Goodbye Cruel World\n");
}
Output
Hello World
I'm the Father and my son's PID is 2749
Goodbye Cruel World
I'm the Son
Goodbye Cruel World
Applications of Fork
- Shell uses fork to run programs
- Google chrome uses fork in order to handle the pages in separate process
- Apache use fork to create multiple server process
Tags:-fork(), fork,c fork, programming, parent, child, process, wait