【问题标题】:Why to fork() and then wait() in parent?为什么要在父级中 fork() 然后 wait() ?
【发布时间】:2012-09-30 11:33:10
【问题描述】:

我知道 fork()、wait()、waitpid()、僵尸进程... 我通过阅读 W. Richard Stevens 来理解他们,这是一本非常好的书。

如果我们不在父节点中调用 wait(),则子节点在终止后会变成僵尸......这很糟糕!

如果我们在 parent 中调用 wait(),则 parent 等待 child 终止,接收终止状态然后继续。 写?

我已经经历了许多调用 fork() 一次然后在父级中调用 wait() 的示例。

但是,如果父级要等待子级并在子级终止后继续,那么就没有实际的多任务处理(技术上是的,有两个进程。但逻辑上没有用)那我们为什么要调用 fork( ) 在这里?

我们可以先编写子代码,然后编写父代码,而不是 fork() 和 wait() 作为单个进程...不是更好吗?

谢谢!

【问题讨论】:

    标签: fork multiprocessing wait zombie-process waitpid


    【解决方案1】:

    有时,即使父级立即阻塞,fork() 也很有用。最常见的情况是当你在做类似于 system() 调用的事情,执行一个外部命令并等待它完成:你会做 fork() + execve()。 (不过,在现代代码中,您应该考虑使用 posix_spawn() 来代替。)

    不过,wait() 不需要阻塞。您可以使用带有标志 WNOHANGwaitpid() 来收集任何已完成进程的退出代码,或者如果它仍在运行则立即继续。

    【讨论】:

      【解决方案2】:

      您在fork()waitpid() 之间编写的代码与子fork 一起同时运行。

      父级等待子级完成,通常只是为了获取子级传递的数据并将其公开给父级。 假设您运行一个主循环,其中任务作为“后台”运行。例如:

      // a simple scheduler
      while(1) {
         if(done_task_1) {
            // if done_task_1 is ever to change in the parent memory scope,
            // parent must know the exit status of its child fork.
            // otherwise there is no way to enter this if sentance, ever
            collect_data_1();
            run_task_1 = 0;
         }
         else if(run_task_1 == 1) {
            // iterate instructions for a sec
            posix_kill(pid_task_1, SIGCONT);
            sleep(1);
            posix_kill(pid_task_1, SIGSTOP);
      
         } 
      
         if(done_task_2) {
            collect_data_2();
            run_task_2 = 0;
         }
         else if(run_task_2 == 1) {
            // iterate instructions for a sec
            posix_kill(pid_task_2, SIGCONT);
            sleep(1);
            posix_kill(pid_task_2, SIGSTOP);
      
         } 
         if(run_task_1 == 0 && run_task_2 == 0) {
             break;
         }
      }
      

      【讨论】:

        猜你喜欢
        • 2020-12-12
        • 1970-01-01
        • 2021-04-19
        • 1970-01-01
        • 2023-04-01
        • 2014-04-21
        • 1970-01-01
        • 1970-01-01
        • 2020-01-22
        相关资源
        最近更新 更多