在C中执行父项之前的子项

时间:2017-02-01 15:59:30

标签: c parallel-processing

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>

int main(int argc, char ** argv)
{

    int pid;
    int status;
    pid = fork();

    if (pid < 0)
    {
        printf("Cannot create a child process");
        exit(1);
    }
    else if (pid == 0)
    {

        printf("I am the child process. %d \n", getpid());
        printf("The child process is done. \n");
        fflush(stdout); // it does not write immediately to a disk.
        exit(0);
    }
    else
    {

        printf("I am the parent process.%d \n", getpid());
        sleep(5); // sleep does not works
        pid = wait(&status); // want to wait until the child is complited
        printf("The parent process is done. \n");
        fflush(stdout); // it does not write immediately to a disk.
        exit(1);
    }
}

大家好,我正在尝试创建一个子进程。到目前为止,这么好,我现在正在尝试的是先执行孩子并打印出来,并始终打印出“父进程已完成”的消息。

I am the parent process.28847  
I am the child process. 28848 
The child process is done.
The parent process is done.

目前正在打印这个:

I am the parent process.28847 
The parent process is done.
I am the child process. 28848 
The child process is done.

这是我第一次使用分叉所以我对我正在做的事情并不是很有信心,我已经尝试过睡眠并等待(和状态)尝试等到子进程完成然后执行父进程但是没有用。

P.S。抱歉布局不好,第一次使用stackoverflow。

1 个答案:

答案 0 :(得分:1)

尝试waitpid(-1,NULL,0);或等待(NULL);这将阻止父级,直到所有子进程完成。 如果它有效,那么你不需要使用睡眠。

对您的代码进行轻微修改:

else
{
    int status =0;
    printf("I am the parent process.%d \n", getpid());
    status= waitpid(-1, NULL, 0); // want to wait until the child is complete
    //Also check if child process terminated properly
    if(status==0)
    {
        printf("Child process terminated properly");
    }   
    else
    {
       printf("Child process terminated with error");
    }

    printf("The parent process is done. \n");

    fflush(stdout); // it does not write immediately to a disk.

    exit(1);
}