c - parent 在 child 进入for循环之前死亡

标签 c unix

我正在尝试创建 2 个 child ,然后他们得到一个参数,告诉他们这 2 个 child 必须像这样创建多少个 child :

http://i.imgur.com/bR3tTNP.png?1

我得到 2 个参数,例如 2 和 3,它们必须创建那么多。我用 for 做到了,它有点管用,但是 parent 在他的第二个 child 去世之前就去世了

edvsil@os:~/4laboras$ ./testas 2 3
pid=389 ppid=387
pid=390 ppid=387
pid=386 ppid=27959
pid=391 ppid=388
edvsil@os:~/4laboras$ pid=387 ppid=1
pid=392 ppid=388
pid=388 ppid=1
pid=393 ppid=388

我的代码:

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

int main( int argc, char *argv[] ){
pid_t child1;
pid_t child2;
int i, a, b;
child1 = fork();
if (child1 != 0){
    child2=fork();
}
if (child1 == 0){
    for (i=1; i<=atoi(argv[1]); i++){
        if (a !=0){
            a=fork();
            if (a == 0){
            printf("pid=%d ppid=%d\n", getpid(),getppid());
            exit(1);
            }
        }
    }
}
else
if (child2 == 0){
    for (i=1; i<=atoi(argv[2]); i++){
        if(b !=0){
            b=fork();
            if (b == 0){
            printf("pid=%d ppid=%d\n", getpid(),getppid());
            exit(1);
            }
        }
    }
}
printf("pid=%d ppid=%d\n", getpid(),getppid());
return 0;
}

最佳答案

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

int main( int argc, char *argv[] ){
    pid_t child1;
    pid_t child2;
    int status;
    int i, a, b;
    child1 = fork();
    if (child1 != 0){
        child2=fork();
    }
    if (child1 != 0 & child2 != 0){
        wait(&status);
    }
    if (child1 == 0){
    for (i=1; i<=atoi(argv[1]); i++){
        if (a !=0){
            a=fork();
            if (a == 0){
                printf("pid=%d ppid=%d\n", getpid(),getppid());
                exit(1);
            }
        }
        }
    }
    else if (child2 == 0){
        printf("pid=%d ppid=%d\n", getpid(),getppid());
        for (i=1; i<=atoi(argv[2]); i++){
            if(b !=0){
                b=fork();
                if (b == 0){
                    exit(1);
                }
            }
        }
    exit(status);
    }
    printf("pid=%d ppid=%d\n", getpid(),getppid());
    return 0;
}

关于c - parent 在 child 进入for循环之前死亡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30491446/

相关文章:

c - 当所有元素都相同时快速排序复杂度?

c - SPARC 和 x86 GCC 一个 C 代码的不同结果

无法从结构成员变量中释放内存

sorting - 对值进行排序并输出其排序列的索引

linux - 如何从当前目录执行添加到 .bashrc 的文件?

Python 守护进程不会在 Ubuntu 的后台运行

c - 循环中的数组元素返回随机大数字(有时为负数)

unix - 使用 Ant 删除隐藏目录中的 Unix 目录

bcopy() 之后客户端的核心转储

c - 我正在尝试找出正确的语法