为什么要在等待后检查WIFEXITED以杀死Linux系统调用中的子进程? [英] Why should we check WIFEXITED after wait in order to kill child processes in Linux system call?
问题描述
我在C语言中遇到了一些代码,我们在其中检查 wait
的返回值,如果这不是错误,则还要对 WIFEXITED
和 WIFEXITSTATUS
.为什么这不是多余的?据我了解,如果发生错误,则 wait
返回-1,而如果 wait
子级正常终止,则 WIFEXITED
返回非零值.因此,如果该行中没有任何错误 if(wait(& status)< 0)
,为什么在 WIFEXITED
检查期间出现任何错误?
I came across some code in C where we check the return value of wait
and if it's not an error there's yet another check of WIFEXITED
and WIFEXITSTATUS
. Why isn't this redundant? As far as I understand wait
returns -1 if an error occurred while WIFEXITED
returns non-zero value if wait
child terminated normally. So if there wasn't any error in this line if ( wait(&status) < 0 )
why would anything go wrong durng WIFEXITED
check?
这是代码:
#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
没有失败),但是它不会告诉您该进程是否成功终止(或是否已发出信号).
wait
returning >= 0
tells you a child process has terminated (and that calling wait
didn't fail), but it does not tell you whether that process terminated successfully or not (or if it was signalled).
但是,在这里,查看您的代码,很明显,程序确实在乎终止的子进程是否成功完成了>
But, here, looking at your code, it's fairly obvious the program does care about whether the child process that terminated did so successfully or not:
fprintf(stderr,子代失败.杀死所有正在运行的子代.\ n");
因此,程序需要对由 wait
填充的 status
结构进行进一步的测试:
So, the program needs to do further tests on the status
structure that was populated by wait
:
-
WIFEXITED(状态)
:该进程是否正常退出?(而不是发出信号). -
WEXITSTATUS(status)== 0
:进程是否以退出代码0(又称为成功")退出.有关更多信息,请参见:Linux返回的退出状态1的含义命令.
WIFEXITED(status)
: did the process exit normally? (as opposed to being signalled).WEXITSTATUS(status) == 0
: did the process exit with exit code 0 (aka "success"). For more information, see: Meaning of exit status 1 returned by linux command.
这篇关于为什么要在等待后检查WIFEXITED以杀死Linux系统调用中的子进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!