Search code examples
operating-systemforkpidsystems-programming

How does fork return a Pid?


I am trying to understand under the hood how does fork return the process id of the child since the child method has not returned, nor does it send by other mechanism its id to the parent. At the lowest level, I do not understand if lets say the child process is a long running loop:

//parent code 
    ...some code...
    Pid=fork([see below])
    ...some code...

//some file containing the executable code of the child process
void childProcessRunningMethod()
{
    while(true);
}

Who is responsible for assigning the Pid to the new process and when does that happen.How does whoever assigns the Pid of the child work.

Does the child method gets overwritten into something like:

void childProcessRunningMethod(string parentPipeAddress)
{
    var somePipe=new Pipe(parentPipeAddress);
    somePipe.Open();
    somePipe.Send([ Pid]); //somehow generates its own Pid
    somePipe.Close();
    
    while(true);
}

Solution

  • under the hood fork looks something as following:

    int fork() {
     1. generate a new PID for child                        // executed only by parent process
     2. do million more things required to create a process // executed only by parent
     /* now we have a new process in the system, which can be scheduled on CPU */
     3. finally return value of a specific CPU register     // executed by both parent and child
     // Note that at this point we have two processes, 
     // in case of child process the CPU register contains 0 (fork returns 0 to child)    
     // in case of parent process register contains PID of child
    }
    

    So as you can see fork in parent process doesn't have to wait for child in order to return the child's PID, as it was already available to parent process.