Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c - fork() code

Tags:

c

void main ()
{
   if ( fork () )
   {
       printf ( "PID1 %d\n", getpid () );
   }
   else
   {
       printf ( "PID2 %d\n", getpid () );
   }
}

What does this code do? I know it has something to do with process IDs but shouldn't fork return something into the condition to determine whether it's a child/parent process?

like image 209
tm1 Avatar asked Mar 09 '10 12:03

tm1


2 Answers

Generally it's:

pid_t pid = fork();
if(pid == 0) {
  //child
} else if(pid > 0) {
  //parent
} else {
 //error
}

The man page says:

RETURN VALUE
   Upon successful completion, fork() shall return 0 to the child 
   process and shall return the process ID of the child process to the 
   parent process.  Both processes shall continue to execute from 
   the fork() function. 
   Otherwise, -1 shall be returned to the parent process, no child process 
   shall be created, and errno shall be set to indicate the error.
like image 104
nos Avatar answered Sep 28 '22 09:09

nos


The above code creates a new process when it executes the fork call, this process will be an almost exact copy of the original process. Both process will continue executing sepotratly at teh return form, the fork call which begs the question "How do i know if im the new process or the old one?" since they are almost identical. To do this the fork designers made the fork call return different things in each process, in the new process (the child) the fork call returns 0 and the original process(the parent) fork returns the ID of the new process so the parent can interact with it.

So in the code the fork call creates a child process, both processes do the if statement seporatly. In the parent the return value is not zero so the parent executes the if statement. In the child the return value is 0 so it does the else statement. Hope this helps :-)

like image 31
PinkyNoBrain Avatar answered Sep 28 '22 07:09

PinkyNoBrain