[英]C Pthreads - Parent/Child
我目前正在编写一个创建子进程的C程序。 创建子进程后,父进程应输出两条消息。 第一个是“我是父母”,第二个是“父母完成了”。 对于子进程“我是孩子”和“孩子完成了”,应该发生相同的情况。 但是,我想确保,孩子的第二条消息总是在父项的第二条消息之前完成。 如何实现此目的,以便打印“孩子完成了”和“父母完成了”而不是打印其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());
}
如果要先执行子级然后执行父级,则应该在父级中使用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;
}
您应该使用wait()
或其表亲之一来阻止父级,直到子级完成。 参见https://linux.die.net/man/2/wait
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.