为什么打印 "This is the child process!" 后执行停止?
Why execution stops after printing "This is the child process!"?
//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;
}
例外的是,从 child 返回后,parent 应该已经执行,但这是我得到的:
$ 这是child过程!
我错过了什么?为什么不打印 child 和 parent 块?
程序完全没问题。执行 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;
}
有关详细信息,请查看此 link:Forking a Process and Parent-Child execution - Linux : C Programming
//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;
}
例外的是,从 child 返回后,parent 应该已经执行,但这是我得到的: $ 这是child过程!
我错过了什么?为什么不打印 child 和 parent 块?
程序完全没问题。执行 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;
}
有关详细信息,请查看此 link:Forking a Process and Parent-Child execution - Linux : C Programming