下面的示例代码来自 linux 手册页 waitpid 函数。最后的else if可以换成else吗?当我写代码的时候,我会这样写:if,else if,以else结尾。所以我觉得在示例代码中很奇怪。
#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
int
main(int argc, char *argv[])
{
pid_t cpid, w;
int status;
cpid = fork();
if (cpid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (cpid == 0) { /* Code executed by child */
printf("Child PID is %ld\n", (long) getpid());
if (argc == 1)
pause(); /* Wait for signals */
_exit(atoi(argv[1]));
} else { /* Code executed by parent */
do {
w = waitpid(cpid, &status, WUNTRACED | WCONTINUED);
if (w == -1) {
perror("waitpid");
exit(EXIT_FAILURE);
}
if (WIFEXITED(status)) {
printf("exited, status=%d\n", WEXITSTATUS(status));
} else if (WIFSIGNALED(status)) {
printf("killed by signal %d\n", WTERMSIG(status));
} else if (WIFSTOPPED(status)) {
printf("stopped by signal %d\n", WSTOPSIG(status));
} else if (WIFCONTINUED(status)) { /* can this be
*replaced with else ???
*/
printf("continued\n");
}
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
exit(EXIT_SUCCESS);
}
}
最佳答案
这是我认为您要问的问题:
Is it possible for
waitpid
to return astatus
such that none ofWIFEXITED(status)
,WIFSIGNALED(status)
,WIFSTOPPED(status)
, orWIFCONTINUED(status)
returns nonzero?
答案几乎肯定是“否”,而 Linux man page没有(不幸的是)明确地说出来就暗示了很多。
UNIX 标准说得更多 here ,并且特别保证其中一个宏在某些情况下将返回非零值。但是 Linux 并不(必然)符合这个标准。
但是 我认为代码中最好的解决方案是在这四个选项之后有一个 else
子句,并且(取决于您的应用程序)认为这意味着状态未知。即使现在不是这种情况,也可能会发生这种情况 - 可能在某些 future 版本的 Linux 中有另一种此处未涵盖的退出条件,并且您不希望您的代码在这种情况下崩溃。
标准似乎确实随着时间的推移而发展。例如,早期版本没有 WIFCONTINUED
大小写,我还在网上找到了一些其他系统中的 WIFCORED
引用资料。因此,如果您担心代码的灵 active ,那将是一件好事。
关于linux - waitpid的用意是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38112922/