为什么wait()在xcode Version 7.2.1(7C1002)上返回-1

时间:2016-03-10 08:02:51

标签: xcode macos fork wait errno

伙计们,我有以下c代码:

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


int main (int argc, char *argv[])
{
    int exit;
    pid_t tc_pid, ret_pid;
    tc_pid = fork();
    if(tc_pid != 0){
        ret_pid = wait(&exit);
        printf("parent process done, tc_pid = %d, ret_pid = %d, errno = %d\n", tc_pid, ret_pid, errno);
        fflush(stdout);
    }
    printf("parent process done, tcpid = %d, my_pid = %d\n", tc_pid, getpid());
    fflush(stdout);

    return 0;
}

xcode上的输出是:

parent process done, tcpid = 0, my_pid = 74377
parent process done, tc_pid = 74377, ret_pid = -1, errno = 4
parent process done, tcpid = 74377, my_pid = 74374

这里wait()的返回值是-1(如果正确的话应该是74377),而errno是-4

但是,当我使用在终端中运行的相同代码(我使用zsh)时,输出为:

parent process done, tcpid = 0, my_pid = 74419
parent process done, tc_pid = 74419, ret_pid = 74419, errno = 0
parent process done, tcpid = 74419, my_pid = 74418

这就是我想要的。有谁知道为什么会发生这种情况?谢谢你们。

我的OSX是10.11.3,我的机器是2015年初的MBPR,xcode 7.2.1, gcc 4.2.1,Apple LLVM版本7.0.2(clang-700.1.81),目标:x86_64-apple-darwin15.3.0,线程模型:posix

1 个答案:

答案 0 :(得分:0)

根据errno.h4的错误为EINTR man page for wait says is

The call is interrupted by a caught signal or the signal does not have the SA_RESTART flag set.

您显然正在使用信号让wait退出。也许你可能需要重新考虑一下你最终在这里尝试做什么,有没有办法在不使用wait的情况下做到这一点?