Thursday, June 17, 2010

fork()

fork()

int fork() turns a single process into 2 identical processes, known as the parent and the child. On success, fork() returns 0 to the child process and returns the process ID of the child process to the parent process. On failure, fork() returns -1 to the parent process, sets errno to indicate the error, and no child process is created. 
NOTE: The child process will have its own unique PID. 

NOTE: The processes have unique ID's which will be different at each run. 
It also impossible to tell in advance which process will get to CPU's time -- so one run may differ from the next. 
When we spawn 2 processes we can easily detect (in each process) whether it is the child or parent since fork returns 0 to the child. We can trap any errors if fork returns a -1. i.e.

int pid; /* process identifier */
 
pid = fork();
if ( pid < 0 )
   { printf(``Cannot fork!!$\backslash$n'');
     exit(1);
   }
if ( pid == 0 )
   { /* Child process */ ...... } 
else
   { /* Parent process pid is child's pid */
   .... }

No comments:

Post a Comment