Search code examples
pidfork

what will be the PID after fork()?


I am doing 3 consecutive forks in a C program.
1. Is it going to execute in the same order ? ( My guess is yes ).
2. If I do a pgrep myexecutable from shell, would it give the process ids in the same order as they were started ? ( my guess is no, because you cant guarantee what pid the system gives the child, right ? )


Solution

  • Shrinath, you should check the documentation for fork(), here it is:

    Upon successful completion, fork() returns a value of 0 to the child
    process and returns the process ID of the child process to the parent
    process.  Otherwise, a value of -1 is returned to the parent process, no
    child process is created, and the global variable errno is set to indi-
    cate the error.
    

    All that means for you, is that means your parent process will get the child's PID when it forks. The child knows it's the child, because fork() will return 0 to the child, so something like:

    if((cpid = fork()))
    { 
      // This is the parent processs, child pid 
      // is in `cpid` variable
    }else{
      // This is the child process, do your child
      // work here.
    }
    

    Beware for the chance that you get a minus number (so there's no child), you should check for that.

    The output of ps will vary by system, but you should see an example, if you look at the whole tree (make your processes sleep, so you have time to check the ps output.)