我正在尝试获取子进程的退出代码。在 Linux 和 FreeBSD 上,我可以这样:
[0] [ishpeck@kiyoshi /tmp]$ uname
FreeBSD
[0] [ishpeck@kiyoshi /tmp]$ cat tinker.c
#include <stdio.h>
#include <sys/wait.h>
int main(void)
{
FILE *proc = popen("ls", "r");
printf("Exit code: %d\n", WEXITSTATUS(pclose(proc)));
return 0;
}
[0] [ishpeck@kiyoshi /tmp]$ gcc tinker.c -o tinker
[0] [ishpeck@kiyoshi /tmp]$ ./tinker
Exit code: 0
[0] [ishpeck@kiyoshi /tmp]$ grep WEXITSTATUS /usr/include/sys/wait.h
#define WEXITSTATUS(x) (_W_INT(x) >> 8)
但是,在 OpenBSD 上,我收到了编译器的抱怨……
[0] [ishpeck@ishberk-00 /tmp]$ uname
OpenBSD
[0] [ishpeck@ishberk-00 /tmp]$ cat tinker.c
#include <stdio.h>
#include <sys/wait.h>
int main(void)
{
FILE *proc = popen("ls", "r");
printf("Exit code: %d\n", WEXITSTATUS(pclose(proc)));
return 0;
}
[0] [ishpeck@ishberk-00 /tmp]$ gcc tinker.c -o tinker
tinker.c: In function 'main':
tinker.c:7: error: lvalue required as unary '&' operand
[1] [ishpeck@ishberk-00 /tmp]$ grep WEXITSTATUS /usr/include/sys/wait.h
#define WEXITSTATUS(x) (int)(((unsigned)_W_INT(x) >> 8) & 0xff)
我真的不在乎它是如何完成的,我只需要退出代码。
这让我相信我在 Mac 上也会遇到这个问题:http: //web.archiveorange.com/archive/v/8XiUWJBLMIKYSCRJnZK5#F4GgyRGRAgSCEG1
有没有更便携的方式来使用 WEXITSTATUS 宏?还是有更便携的选择?