我目前正在编写一个创建子进程的 C 程序。创建子进程后,父进程应该输出两条消息。第一个是“我是 parent ”,第二个是“ parent 已经完成”。对于子进程“我是 child ”和“ child 已经完成”也应该发生同样的情况。但是我想确保, child 的第二条消息总是在 parent 的第二条消息之前完成。我怎样才能实现这一点,以便打印“ child 完成”和“ parent 完成”而不是打印他们的 pid?
这是我目前拥有的:
#include <unistd.h>
#include <stdio.h>
main()
{
int pid, stat_loc;
printf("\nmy pid = %d\n", getpid());
pid = fork();
if (pid == -1)
perror("error in fork");
else if (pid ==0 )
{
printf("\nI am the child process, my pid = %d\n\n", getpid());
}
else
{
printf("\nI am the parent process, my pid = %d\n\n", getpid());
sleep(2);
}
printf("\nThe %d is done\n\n", getpid());
}
最佳答案
如果你想先执行child,然后执行parents,那么你应该在parents中使用wait(),在child中使用exit()。
使用 exit()
将子级 status
发送给父级。
int main() {
int pid, stat_loc;
printf("\nmy pid = %d\n", getpid());
pid = fork();
if (pid == -1) {
perror("error in fork");
return 0;
}
else if (pid ==0 ) {
printf("\nI am the child process, my pid = %d\n\n", getpid());
sleep(5);
exit(0);/* sending child status */
}
else {
int status = 0;
int ret = wait(&status);/* wait() returns pid of the child for which its waiting */
printf("\nThe %d is done\n\n", ret);
printf("\nI am the parent process, my pid = %d\n\n", getpid());
}
printf("\nThe %d is done\n\n", getpid());/* getpid() returns pid of the process */
return 0;
}
关于C Pthreads - 父/子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48733293/