c - 为什么我们要在 wait 之后检查 WIFEXITED 以便在 Linux 系统调用中杀死子进程?

标签 c linux unix operating-system

我在 C 中遇到了一些代码,我们在其中检查 wait 的返回值如果这不是错误,则会再次检查 WIFEXITEDWIFEXITSTATUS .为什么这不是多余的?据我了解wait如果在 WIFEXITED 期间发生错误,则返回 -1如果 wait 则返回非零值 child 正常终止。因此,如果此行中没有任何错误 if ( wait(&status) < 0 )为什么在 WIFEXITED 期间会出什么问题?检查?

这是代码:

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

#define CHILDREN_NUM 5

int main () {

    int i, status, pid, p;
    for(i = 0; (( pid = fork() ) < 0) && i < CHILDREN_NUM;i++)
        sleep(5);


    if ( pid == 0 )
    {
        printf(" Child %d : successfully created!\n",i);
        exit( 0 );  /* Son normally exits here! */
    }

    p = CHILDREN_NUM;
    /* The father waits for agents to return succesfully */
    while ( p >= 1 )
    {
        if ( wait(&status) < 0 ) {
            perror("Error");
            exit(1);
        }

        if ( ! (WIFEXITED(status) && (WEXITSTATUS(status) == 0)) )  /* kill all running agents */
        {
            fprintf( stderr,"Child failed. Killing all running children.\n");
           //some code to kill children here
            exit(1);
        }
        p--;
    }

    return(0);
}

最佳答案

wait 返回 >= 0 告诉您子进程已终止(并且调用 wait 没有失败),但它确实不会告诉您该进程是否成功终止(或者是否收到信号)。

但是,在这里,查看您的代码,很明显该程序确实关心终止的子进程是否成功完成:

fprintf( stderr,"Child failed. Killing all running children.\n");

因此,程序需要对wait填充的status结构做进一步的测试:

关于c - 为什么我们要在 wait 之后检查 WIFEXITED 以便在 Linux 系统调用中杀死子进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47441871/

相关文章:

c++ - 如何使用 putenv 系统调用维护内存?

c++ - 在 C 和 C++ 中,为什么每个 .h 文件通常都用#ifndef#define #endif 指令包围?

c - 有谁知道我的 C 程序的这种奇怪输出是如何发生的?

c - 使用 O_APPEND 的 open() 不会更新 EOF

linux - 在 bash 脚本中调用 SSH Sudo 命令

在 UNIX 中复制目录的 C 函数 : files fail to copy

c - C 中未使用函数的影响

c - 将位字段与 union 一起使用是否有效?

linux - 在 Windows 主机和 Linux guest 之间使用 Hyper-V 套接字

linux - 输出特定字符的所有列号