gpt4 book ai didi

c - 在 C 中先于父执行子

转载 作者:太空宇宙 更新时间:2023-11-04 03:24:52 26 4
gpt4 key购买 nike

#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.

这是我第一次使用 fork ,所以我对自己在做什么不太有信心,我试过 sleep 和等待(&status)来尝试等到子进程完成然后执行父进程,但有些事情不是工作。

附言抱歉布局不好,第一次使用 stackoverflow。

最佳答案

试试 waitpid(-1, NULL, 0);或等待(NULL);这将阻塞父进程,直到所有子进程都完成。如果有效,则您无需使用 sleep 。

对您的代码稍作修改:

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);
}

关于c - 在 C 中先于父执行子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41984209/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com