我编写此代码是为了使用进程和pipe()计算数字的阶乘。我想将结果从子进程传递到子进程。例如创建计算5!父亲的主要人在管道中发送数字1。然后,第一个孩子创建并执行1 * 2,然后将数字2推入管道,第二个孩子执行2 * 3将结果推入管道等。此外,我使用argv [1] [0]认为我们这样运行程序(./ex3 5),其中5是我们要查找的阶乘数。在运行程序之后,我注意到创建了许多子进程(我只想要4个)。这是为什么?

#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>

int fd[2];
int w,count=2;

void child_creator(){
    pid_t child;
    child=fork();
    if (child==0) {
        close(fd[1]);
        read(fd[0],&w,sizeof(w));
        close(fd[0]);
        w=w*count;
        count++;
        printf("I am child %d , my father is %d , the prod is %d\n",getpid(),getppid(),w);
        sleep(1);

        close(fd[0]);
        write(fd[1],&w,sizeof(w));
        close(fd[1]);
    }
}

int main(int argc , char **argv){
    int fact=argv[1][0]-'0';
    pipe(fd);
    w=1;
    for (int i=0; i<fact-1; i++){
         printf("this is i %d\n", i);
        child_creator();
    }
    return 0;
}


在提出建议的答案后,我尝试了以下代码:

#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>

int fd[1000][2];
int w,count=1,j=0;

void child_creator(){
    pid_t child;
    j++;
    pipe(fd[j]);
    child=fork();
    if (child==0) {
        close(fd[j-1][1]);
        read(fd[j-1][0],&w,sizeof(w));
        close(fd[j-1][0]);
        w=w*count;
        printf("I am child %d , my father is %d , the prod is %d\n",getpid(),getppid(),w);
        sleep(1);

        close(fd[j-1][0]);
        write(fd[j][1],&w,sizeof(w));
        close(fd[j][1]);

        exit(0);

    }

}

int main(int argc , char **argv){
    int fact=argv[1][0]-'0';
    w=1;
    for (int i=0; i<fact-1; i++){
     count++;
     child_creator();
     sleep(2);
    }

    return 0;
}

最佳答案

父级和子级都将返回到for中的main()循环。由于孩子在写入结果后不需要执行任何操作,因此应该退出而不是返回。

您在处理管道文件描述符时也遇到了问题。您在孩子开始时做close(fd[1]),但是稍后尝试write(fd[1],&w,sizeof(w))。您无法写入封闭的FD。在子项退出之前,您不需要关闭任何内容,退出进程会自动关闭其所有文件。

void child_creator(){
    pid_t child;
    child=fork();
    if (child==0) {
        read(fd[0],&w,sizeof(w));
        w=w*count;
        count++;
        printf("I am child %d , my father is %d , the prod is %d\n",getpid(),getppid(),w);
        sleep(1);
        write(fd[1],&w,sizeof(w));
        exit(0);
    }
}

关于c - 为什么此功能会产生这么多子进程?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55270469/

10-11 22:07
查看更多