打印后为什么执行会停止“这是子进程!”?

时间:2016-05-14 11:34:29

标签: c process fork

//Why not execute all the conditions(parent and child)?
#include<stdio.h>
#include<unistd.h>

int main(){
        pid_t pid; //process-id
        printf("This is where we start...\n");
        pid = fork();
//For the child process
        if(pid==0){
                printf("This is the child process!\n");
                return 1;
        }
//This should have been printed
        if(pid>0){
                printf("This is the parent!\n");
        }
//THis may/may not be printed - its ok
        if(pid < 0){ 
                printf("Fork failed!");
        }
        return 0;
}

除了从孩子回来后,父母本应该被处决,但这是我得到的: $这是孩子的过程!

我缺少什么?为什么不打印孩子和父母一块?

1 个答案:

答案 0 :(得分:3)

该计划完全没问题。执行fork时,将创建一个新的子进程。创建的子进程独立于父进程,父进程完全可能不等待子进程完成执行。

如果你希望子进程完成后父进程恢复,你应该使用wait()函数,这样可以确保在父进程继续之前执行分叉子进程。

尝试更新您的代码,如下所示:

#include<stdio.h>
#include<unistd.h>
#include <sys/wait.h>  //Add this header

int main()
{
        pid_t pid; //process-id
        int status;  //A variable to get the status of the child, i.e. if error or success
        printf("This is where we start...\n");
        pid = fork();
        if(pid==0){
                printf("This is the child process!\n");
                return 1;
        }
        if(pid>0){
                wait(&status);   //Function to wait for child
                printf("This is the parent!\n");
        }
        if(pid < 0){ 
                printf("Fork failed!");
        }
        return 0;
}

有关详细信息,请查看此链接:Forking a Process and Parent-Child execution - Linux : C Programming