开发者

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?


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.


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 :-)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜