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 this has something to do with process identifiers, but shouldn't the fork return something to the condition to determine if this is a child / parent process?

+6
c
source share
3 answers

Usually this:

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

The manual 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.
+16
source share

The above code creates a new process, when it makes a fork call, this process will be an almost exact copy of the original process. Both processes will continue to execute sepotratly in the form of a return, fork call, which raises the question "How do I know if im a new process or an old one?" since they are almost identical. To do this, the fork developers made the fork call return different things in each process, in the new process (child), the fork call returns 0, and the original (parent) fork returns the identifier of the new process so that the parent can interact with it.

Thus, in the code, calling fork creates a child process, both processes execute the if seporatly statement. In the parent, the return value is not zero, so the parent operator executes the if statement. In the child case, the return value is 0, so it executes the else statement. Hope this helps :-)

+3
source share

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

-2
source share

All Articles