繁体   English   中英

此摘录中创建了多少个进程?

[英]How many processes are created in this excerpt of code?

你能帮我吗? 我对流程的创建有些困惑,我认为创建的流程数量为7,对吗?

int main(){
    pid_t pid;
    int i;
    for (i = 0; i < 3; i++){
        pid = fork();
        if(pid > 0){
            printf("I'm father\n");
        }else{
            sleep(1);
        }
    }

    return 0;
}

没错,分叉了7个流程(还有原始的父流程,总共有8个)。 关键概念是分叉进程最初是其父进程的(近)精确副本,因此特别是它们具有相同的变量值,并从fork()调用返回开始执行。 下表列出了程序中将发生的派生:

  i  proc0  proc1  proc2  proc3  proc4  proc5  proc6  proc7
 -----------------------------------------------------------------
  0    +1    new
  1    +1     +1    new    new
  2    +1     +1     +1     +1    new    new    new    new

+1表示分叉; 将它们加起来得到7。当i == 2 ,将创建派生进程4-7,但是它们自己不要分叉,因为它们在这样做之前会掉出循环的底部(而他们的父母在可能之前掉出了底部)再次分叉)。

还要注意,进程proc2 - proc7的标签不会直接传达有关父母proc7或创建顺序的信息; 该表仅在分叉变量时将每个标签与变量i的值相关联,并描述了每个进程在开始运行时作为其i值的函数进行分叉的次数。

如果在创建子代时从子代打印一条消息,则更容易看到发生了什么。

#include <stdio.h>
#include <unistd.h>

int main( void )
{
    pid_t pid;
    for ( int i = 0; i < 3; i++ )
    {
        pid = fork();
        if (pid > 0)
            sleep(1);       // give the child time to print its message
        else if (pid == 0)
            printf( "I'm child %d, my parent is %d\n", getpid(), getppid() );
    }
}

样本输出:

I'm child 308, my parent is 307
I'm child 309, my parent is 308
I'm child 310, my parent is 309
I'm child 312, my parent is 308
I'm child 311, my parent is 307
I'm child 313, my parent is 311
I'm child 314, my parent is 307

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM