tags:

views:

181

answers:

3
+5  Q: 

c - fork() code

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?

+15  A: 

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.
nos
Ahh ok thank you.Edit:Yeah I see many examples like that too, hence why I got confused.
tm1
+1 for checking for errors!
Philip Potter
if ( fork () ) // if fork successful...................... printf ( "PID1 %d\n", getpid () ); // print parentID...................... else printf ( "PID2 %d\n", getpid () ); // print child id
tm1
Is that right? Sorry don't know the code tags.
tm1
@tm1: `if (fork())` will be true either if the fork was successful and you are in the parent, OR if the fork failed. nos's code distinguished between success and failure by explicitly checking for a positive return value from `fork()`. PS markup documentation is available in the FAQ, at the top of the page.
Philip Potter
A: 

The return value of fork() indicates whether the process is the parent or the child. So the child will always print "PID2 0", because if fork() returns 0, the second part of the if statement is run.

Sjoerd
doesn't `getpid()` return the actual PID of current process no matter what `fork()` returns?
SF.
@SF: sounds right to me.
John Zwinck
+2  A: 

Hi tm1. 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 :-)