我在 C 中遇到了一些代码,我们在其中检查 wait
的返回值如果这不是错误,则会再次检查 WIFEXITED
和 WIFEXITSTATUS
.为什么这不是多余的?据我了解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
结构做进一步的测试:
WIFEXITED(status)
:进程是否正常退出? (与发出信号相反)。WEXITSTATUS(status) == 0
:进程是否以退出代码 0 退出(也称为“成功”)。有关详细信息,请参阅:Meaning of exit status 1 returned by linux command .
关于c - 为什么我们要在 wait 之后检查 WIFEXITED 以便在 Linux 系统调用中杀死子进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47441871/