【问题标题】:Forking multiple child and wait till the child processes die分叉多个子进程并等待子进程死亡
【发布时间】:2016-09-22 08:44:55
【问题描述】:

我必须编写一个程序来分叉 3 个子进程。

然后父进程只显示一次自己的PID信息,然后等待其子进程死亡。

所有子进程终止后,主进程显示“主进程终止”然后退出。

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>

int main( int argc, char *argv[], char *env[] )
{
       pid_t my_pid, parent_pid, child_pid;
       int status;

    /* get and print my pid and my parent's pid. */

       my_pid = getpid();    parent_pid = getppid();
       printf("\n Parent: my pid is %d\n\n", my_pid);
       printf("Parent: my parent's pid is %d\n\n", parent_pid);

    /* print error message if fork() fails */
       if((child_pid = fork()) < 0 )
       {
          perror("fork failure");
          exit(1);
       }

    /* fork() == 0 for child process */

       if(child_pid == 0)
       {
          execl("/bin/date", "date", 0, 0);


          printf("This print is after execl() and should not have been executed if execl were successful! \n\n");

          _exit(1);
       }
    /*
     * parent process
     */
       else
       {
          printf("\nParent: I created a child process.\n\n");
          printf("Parent: my child's pid is: %d\n\n", child_pid);
          wait(&status); /* can use wait(NULL) since exit status
                            from child is not used. */
          printf("\n Parent: my child is dead. I am going to leave.\n \n ");
       }

       return 0;
}

【问题讨论】:

  • 好吧,如果你迫切需要这个,那么你可能应该花时间编写这个而不是问关于 SO 的离题问题。这不是gimmetehcodez.biz。如果您在代码中遇到特定问题,在您尝试自己研究和解决它之后,如果您在问题中展示了此类研究和解决方案尝试,我们可以为您提供帮助。但我们不会为您编写代码。
  • 让它与一个子进程一起工作似乎是一个不错的起点。
  • 相关的C库调用有fork、system、waitpid。去手册页中查找它们。或者阅读 Richard W. Stevens 的名著《UNIX 环境中的编程》。
  • 我使用了一个子进程,需要与 3 个子进程一起完成才能终止并将其跳转到主进程@molbdnilo
  • 我们可以看看你目前拥有的代码吗,@ahnaf22?请将其编辑到您的问题中。

标签: c++ unix networking


【解决方案1】:

对不起,我想写评论,但我没有足够的声誉。 如果你想先显示父pid。那么你可以在fork()之前使用getpid(),然后你可以使用waitpid进行收割。可能需要一个循环来收割所有三个孩子。

【讨论】:

  • 请举例?
猜你喜欢
  • 1970-01-01
  • 2018-02-22
  • 1970-01-01
  • 2011-06-24
  • 1970-01-01
  • 2011-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多