[英]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.