我尝试使用'fork'创建一个进程

时间:2017-11-24 12:11:32

标签: c linux

我开始研究叉子了。使用fork时,我遇到了一些问题。 我正在尝试用两个孩子创建单个父进程 两个孩子试图让每三个孙子。 当我运行我的代码时,与我的期望不同,这么多的孩子和孙子出来了。

这是我的代码:

int main()
{
    int i, j, rev;

    for(i=0;i<2;i++)
    {
        if((rev=fork())<0) { printf("fork() error\n"); exit(-1); }
        else if(rev==0)
        {
            printf("child %d %d \n",getpid(),getppid());

            for(j=0;j<3;j++)
            {
                if((rev=fork()) <0) { printf("fork() error\n"); exit(-1); }
                else if(rev == 0)
                {
                    printf("grandch %d %d \n",getppid(),getpid());
                    exit(0);
                }
            }

        }
    }
    printf("parent %d %d \n",getpid(),getppid());
    exit(0);
}

如何更正此代码?

2 个答案:

答案 0 :(得分:4)

使用fork()语句之前的一个重要示例

//Calculate number of times hello is printed.
#include  <stdio.h>
#include  <sys/types.h>
int main()
{
    fork();
    fork();
    fork();
    printf("hello\n");
    return 0;
}

打印的次数等于创建的进程数。总进程数= 2 ^ n 其中n是fork系统调用的数量。所以这里n = 3,2 ^ 3 = 8。

fork ();   // Line 1
fork ();   // Line 2
fork ();   // Line 3

       L1       // There will be 1 child process 
    /     \     // created by line 1.
  L2      L2    // There will be 2 child processes
 /  \    /  \   //  created by line 2
L3  L3  L3  L3  // There will be 4 child processes 
                // created by line 3
  

所以,如果你想要两个孩子的过程然后三个盛大   孩子遵循这类事情:

对于两个子进程

,您应该做的是这样的事情
if(fork()) # parent
    if(fork()) #parent
    else # child2
else #child1

创建流程后,应检查返回值。如果不这样做,第二个fork()将由父进程和子进程执行,所以你有四个进程。

如果您想创建 n子流程,只需:

for (i = 0; i < n; ++i) {
    pid = fork();
    if (pid) {  //means pid is non-zero value, i.e, pid>0
        continue;
    } else if (pid == 0) {
        break;
    } else {
        printf("fork error\n");
        exit(1);
    }
}

答案 1 :(得分:1)

为子进程运行的代码部分不会退出。结果,他们继续运行外循环的更多迭代,只有父进程才能运行,因此它们会产生更多的子进程。

您需要致电exit,或者更好_exit,以便孩子们不要这样做:

int main()
{
    int i, j, rev;

    for(i=0;i<2;i++)
    {
        if((rev=fork())<0) { printf("fork() error\n"); exit(-1); }
        else if(rev==0)
        {
            printf("child %d %d \n",getpid(),getppid());

            for(j=0;j<3;j++)
            {
                if((rev=fork()) <0) { printf("fork() error\n"); exit(-1); }
                else if(rev == 0)
                {
                    printf("grandch %d %d \n",getpid(),getppid());
                    _exit(0);
                }
            }

            sleep(1);      // stick around so the grandchild can print the parent pid
            _exit(0);      // exit the child
        }
    }
    printf("parent %d %d \n",getpid(),getppid());
    sleep(1);   // stick around so the child can print the parent pid
    exit(0);
}
相关问题