c - 使用 fork() 时收割子进程

标签 c multithreading fork

我试图在使用 fork() 并行运行两个命令时获取子进程。我使用以下代码执行此操作:

int process() {
    int w, status;  
    while ((w = waitpid(-1,&status,WNOHANG)) > 0)                               
         fprintf(stderr,"Completed: %d (%d)\n",w,status);

    int pid;                                                                
    if ((pid = fork()) < 0)                                                 
       errorExit (EXIT_FAILURE);                                           

    if (pid == 0) {                                                         
        // run first command                                            
    } else if (cmdList->right) {                                            
        // run second command                                           
    } 
}

我对这段代码的理解是:我在程序运行时持续运行 waitpid() ,并且每当 waitpid() 返回大于 0 的值时,它报告它(从而允许僵尸死亡),然后执行 fprintf()stderr。这种理解有错吗?

最佳答案

此代码将确保删除所有终止的子项,如标志所示:

WNOHANG

The waitpid() function shall not suspend execution of the calling thread if status is not immediately available for one of the child processes specified by pid.

Ref

所以当你遇到这类 child 时,你就会执行fprintf()。因此,如果您有两个这样的子级,则 fprintf() 将执行两次。 fprintf() 将写入 stderr

请注意,在执行该循环之后,您将再次调用 fork(),这将创建一个子级,该子级不会由循环处理。

关于c - 使用 fork() 时收割子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26986657/

相关文章:

Node.js、集群模式、日志聚合和logrotate

c - 如何在 linux 内核中实现 clone(2) 系统调用的另一种变体?

c - 使用 gcc 将汇编代码与 C 代码链接的正确方法是什么

c++ - 用两条语句并行化 while 循环(Floyd 循环检测算法)

java - 为什么主线程在继续之前等待另一个线程完成?

c++ - 如何测试 std::memory_order_relaxed 的行为?

c - Kochan 的 C 编程练习 7.12

c - 检查字符串中的数字字母

c - 将 Quake 2 中的 MASM5 代码移植到 GAS——意外的渲染结果

c - fork() 中的父 ID 和提前终止