Fork和exec在Linux中有几个孩子

时间:2018-11-28 19:42:51

标签: c linux gcc

我想从另一个分支并执行几个进程。 我的父代码是

/*Daddy.c*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
    int main(void)
{
        int status;
        char *nChild;

        for (int i=0; i<3;i++){
            int pid = fork();
            if (pid == 0)
            {
                sprintf(nChild, "%d", i);
                printf("%d\n", i);
                char *const arguments[]={nChild, NULL};
                fflush(NULL);
                execv("child",arguments);
                printf("\nNo , you can't print!\n");
            }else if (pid == -1){
                    printf("%d\n", getpid());
                    exit(0);
            }
        }
        wait(&status);
        printf("Dad %d went out!\n", getpid());
        exit(0);
}

我的子进程是

    /*child.c*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int args, char **argv){
        if( args !=2){
                printf("Child going away!\n");
                exit(1);
        }
        printf("Child %s: %d going away stylishly!\n", argv[1], getpid());

        exit(0);
}

当我不创建三个叉子时,我知道如何创建孩子,做一些工作并退出孩子和父母。但是,在这种情况下,有多个孩子似乎孩子永远不会执行。 由于行wait(&status),我确实希望当第一个孩子退出时,父级也退出,但是任何孩子都会打印任何消息。 Some relevant previous questions没有帮助。

2 个答案:

答案 0 :(得分:1)

您需要让父级等待所有子级进程完成。如果不是,则假设1个等待的孩子完成,然后父母退出。那另外两个孩子呢?他们成为孤儿,因为他们的父母不等他们。

cond_t

答案 1 :(得分:0)

此代码完成了工作

/* daddy.c */
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <string.h>
int main(void)
{
        int status=0;
        char nChild[16];
        pid_t wpid;
        for (int i=0; i<3;i++){
            sprintf(nChild, "%d", i);
            int pid = fork();
            if (pid == 0)
            {
                printf("%s\n", nChild);
                char *const arguments[]={"child", nChild, NULL};
                fflush(NULL);
                execv("child",arguments);
                printf("\nNo , you can't print!\n");
            }else if (pid == -1){
                    printf("%d\n", getpid());
                    exit(0);
            }
        }
        while ((wpid=wait(&status)) >0);
        printf("Dad %d went out!\n", getpid());
        exit(0);
}

正如@OnzOg在问题评论中所说,nChild的分配是主要问题。另外execv需要两次传递子名称,一个作为参数。 最后,为了改进代码,父进程需要等待所有进程完成。