c - 涉及for循环的fork函数

标签 c linux fork

我在尝试解决这个问题时遇到了很大的痛苦。因此,我想做的是创建 3 个源自一个父进程的子进程。我已经弄清楚了,但问题是我的程序在到达第三个 child 时退出,使其成为孤儿(我认为)。这是我的第一代进程的代码:

int i = 0;
int corpse;
int status;
pid_t child;
about("Dad");
printf("Now ..  Forking !!\n");

about("Dad");
for(i=0; i<3; i++){
child = fork();

  if (child == 0){

    about ("son");
    break;

  }else if (child < 0){

    perror ("Unable to fork!");
    break;
  }

}

void about(char * msg)
{
 pid_t me;
 pid_t old;

 me = getpid();
 old = getppid();

 printf("[%s] Hi, my pid is %d and I come from %d.\n", msg, me, old);
}
while ((corpse = wait(&status)) > 0){
    printf("Child process PID=%d terminates\n", corpse);
}

现在我的输出如下:

[Dad] Hi, my pid is 2940 and I come from 2883.
Now ..  Forking !!
[Dad] Hi, my pid is 2940 and I come from 2883.
[son] Hi, my pid is 2941 and I come from 2940.
[son] Hi, my pid is 2942 and I come from 2940.
Child process PID=2941 terminates
Child process PID=2942 terminates
[son] Hi, my pid is 2943 and I come from 2940.
Child process PID=2943 terminates

最佳答案

如果我能猜对的话,你担心子进程会成为孤儿进程,那么你可以使用wait或waitpid。通过使用其中任何一个,父进程可以等待子进程终止。 如需更多帮助,请使用“man wait”。

关于c - 涉及for循环的fork函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26075216/

相关文章:

创建带孔的文件

linux - 通过 Linux 脚本或 falcon 更新文本文件中的日期和时间 : Hadoop

linux - 我无法从我的 Linux 系统中卸载 Tcl

c++ - unix-fork-monitor-child-progress

C:父子进程

c - 在 c 中使用 p 线程编写并行快速排序

c - 在 C 中获取临时(复合文字)参数的地址

c - C 编程中使用 for 循环写入文件

c - 如何避免在控制台上打印来自 syslog 的广播消息

C 父级和 2 个子级之间的管道