【问题标题】:How does fork return a Pid?fork 如何返回一个 Pid?
【发布时间】:2021-02-07 03:40:23
【问题描述】:

我试图了解 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-system fork pid systems-programming


    【解决方案1】:

    在后台 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,因为它已经可供父进程使用。

    【讨论】:

      猜你喜欢
      • 2017-02-14
      • 2013-02-26
      • 1970-01-01
      • 2019-01-13
      • 1970-01-01
      • 2013-09-25
      • 1970-01-01
      • 1970-01-01
      • 2014-02-24
      相关资源
      最近更新 更多