Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 创建新流程_C_Process_Fork - Fatal编程技术网

C 创建新流程

C 创建新流程,c,process,fork,C,Process,Fork,我通过分叉创建新流程: printf("original process = %d\n", getpid()); fork(); printf("parent = %d; child = %d\n", getpid(), getppid()); fork(); printf("parent = %d; child = %d\n", getpid(), getppid()); if(fork() == 0){ printf("parent = %d; child = %d\n",

我通过分叉创建新流程:

printf("original process = %d\n", getpid());
fork();
printf("parent = %d; child = %d\n", getpid(), getppid());
fork();
printf("parent = %d; child = %d\n", getpid(), getppid());
if(fork() == 0){
        printf("parent = %d; child = %d\n", getpid(), getppid());
        if(fork() == 0){
                    printf("parent = %d; child = %d\n", getpid(), getppid());
        }    
}
fork();
printf("parent = %d; child = %d\n", getpid(), getppid());

我想打印出我创建了多少个进程。如上所述,我的方法不是打印创建了多少进程的最佳方法。所以我的问题是:我们如何在没有某种循环的情况下,打印出每次分叉时创建了多少个新流程

每次成功调用fork都会创建一个新进程,父进程和子进程都从
fork()
返回。子级将得到0作为返回,父级将得到子级的PID

printf("I am the root %d\n", getpid());
if (fork() == 0)
    printf("I am %d, child of %d\n", getpid(), getppid());
if (fork() == 0)
{
    printf("I am %d, child of %d\n", getpid(), getppid());
    if (fork() == 0)
        printf("I am %d, child of %d\n", getpid(), getppid());
}
if (fork() == 0)
    printf("I am %d, child of %d\n", getpid(), getppid());
等等


代码中的问题是,在某些情况下打印文本时没有检查
fork()
的返回值,因此这些行将同时由父级和子级打印。使用我的代码,每个进程在创建时只打印一行。

当每个进程创建/生成一个子进程时,
基于fork()的调用顺序
总共创建了24个子进程,就是这样完成的

1st fork();(有更多的fork()调用)
2st fork();(有3个以上的fork()调用)
3st拨叉();(有2个以上的fork()调用)
4st fork();(有更多的fork()调用)

因此子进程的总数将4!-1,即4x3x2x1=24-1

创建了23个子进程

我数了18个,但我可能遗漏了什么。而
getppid()
不返回子进程id。它返回活动的父进程id。I bid 2*2*2*2+2*2-1=19。