//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;
}
异常(exception)的是,从 child 那里回来后, parent 应该被处决,但这是我得到的: $ 这是子进程!
我错过了什么?为什么不打印子 block 和父 block ?
最佳答案
程序完全没问题。执行 fork 时,会创建一个新的子进程。创建的子进程独立于父进程,父进程完全有可能不等待子进程完成执行。
如果您希望在子进程完成后继续执行父进程,您应该使用 wait() 函数,以确保在父进程继续之前执行 fork 的子进程。
尝试按如下方式更新您的代码:
#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
关于c - 为什么在打印 "This is the child process!"后执行停止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37226137/