c - 父子进程打印

标签 c multithreading pthreads fork

我正在编写一个创建子进程的 C 程序。创建子进程后,父进程应该输出两条消息:“I am the parent”然后它应该打印“The parent is done”。对于子进程“我是 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());
}

最佳答案

您可以有一个标志变量,它在父级中设置,但随后子级将其清除。然后简单地检查最后的输出。

有点像

int is_parent = 1;  // Important to create and initialize before the fork

pid = fork();

if (pid == -1) { ... }

if (pid == 0)
{
    printf("\nI am the child process, my pid = %d\n\n", getpid());
    in_parent = 0;  // We're not in the parent anymore
}
else { ... }

printf("\nThe %s is done\n\n", is_parent ? "parent" : child");

关于c - 父子进程打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35116512/

相关文章:

java - 关闭 ScheduledExecutorService 是否安全?

c - pthread 完成后打印变量

c - 将大量线程固定到单个 CPU 会导致所有内核的利用率激增

c - 分离数据并存储在数组中

c - C中的字符串数组在内存中是什么样子的?

c - 无法从函数获取字符串并在不重复 strcpy 和 strcat 命令的情况下显示

c++ - 代码单步如何与线程一起工作?

php - 在php中使用pthread进行Multiupload

c - 线程中的线程?

c++ - 是否可以在 .mm 文件中仅使用 C 语法?