The fork() Function
The fork() function is used to create a new process by duplicating the existing process from which it is called. The existing process from which this function is called becomes the parent process and the newly created process becomes the child process. As already stated that child is a duplicate copy of the parent but there are some exceptions to it.
The child has a unique PID like any other process running in the operating system.
The child has a parent process ID which is same as the PID of the process that created it.
Resource utilization and CPU time counters are reset to zero in child process.
Set of pending signals in child is empty.
Child does not inherit any timers from its parent
Note that the above list is not exhaustive. There are a whole lot of points mentioned in the man page of fork(). I’d strongly recommend readers of this article to go through those points in the man page of fork() function.
The Return Type
Fork() has an interesting behavior while returning to the calling method. If the fork() function is successful then it returns twice. Once it returns in the child process with return value ’0′ and then it returns in the parent process with child’s PID as return value. This behavior is because of the fact that once the fork is called, child process is created and since the child process shares the text segment with parent process and continues execution from the next statement in the same text segment so fork returns twice (once in parent and once in child).
An Example:-
#include<stdio.h>
#include<pthread.h>
int main()
{
int i=20,ret;
pthread_t p_id;
printf("before fork\n");
ret=fork();
if(ret==0)
{
printf("child:\n");
i=19;
printf("i value for the child=%d",i);
}
else
{
printf("parent:\n");
i=30;
printf(" i value for the parent=%d",i);
}
printf("belongs to both%d\n",i);
return 0;
}
Comments