【问题标题】:C Pthreads - Parent/ChildC Pthreads - 父/子
【发布时间】:2018-02-11 15:46:51
【问题描述】:

我目前正在编写一个创建子进程的 C 程序。创建子进程后,父进程应该输出两条消息。第一个是“我是父母”,第二个是“父母已经完成”。子进程“I am the child”和“The child is done”也应该如此。但是我想确保,孩子的第二条消息总是在父母的第二条消息之前完成。我怎样才能做到这一点,以便打印“孩子完成”和“父母完成”而不是打印他们的 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());
}

【问题讨论】:

  • pthreads 与问题有何关系?如果没有,请删除标签并在问题中提及它。

标签: c fork parent-child


【解决方案1】:

如果你想先执行 child 先 然后再执行 parents,那么你应该使用 wait() in parentsexit() in child

使用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;
}

【讨论】:

    【解决方案2】:

    您应该使用wait() 或其表亲之一来阻止父级,直到子级完成。见https://linux.die.net/man/2/wait

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多