首页 > 解决方案 > fork 如何返回一个 Pid?

问题描述

我试图在幕后理解如何fork返回子进程的进程 ID,因为子方法没有返回,也没有通过其他机制将其 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给新流程以及何时发生。分配Pid孩子的人如何工作。

子方法是否被覆盖为:

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

标签: operating-systemforkpidsystems-programming

解决方案


引擎盖下的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
}

因此,正如您fork在父进程中看到的那样,父进程process不必等待子进程才能返回子PID进程,因为它已经可供父进程使用。


推荐阅读