如何 fork return 一个 Pid?

How does fork return a Pid?

我试图深入了解 fork return 子进程的进程 ID,因为子方法没有 returned,也不由其他方法发送将其 id 机制传递给父级。在最低级别,我不明白是否可以说子进程是一个长 运行 循环:

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

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

谁负责将 Pid 分配给新进程以及何时分配 happen.How 谁分配 Pid 子进程。

子方法是否被覆盖为类似的东西:

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

在引擎盖下 fork 看起来如下所示:

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
}

因此,正如您在 parent 中看到的 fork process 不必等待 child 即可 return child 的 PID,因为它已经可供 parent 进程使用。