【问题标题】:why wait() return -1 on xcode Version 7.2.1 (7C1002)为什么 wait() 在 xcode 版本 7.2.1 (7C1002) 上返回 -1
【发布时间】:2016-03-10 08:02:50
【问题描述】:

各位,我有以下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

【问题讨论】:

    标签: xcode macos fork wait errno


    【解决方案1】:

    根据errno.h4的errno是EINTRman 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 的情况下做到这一点?

    【讨论】:

    • 嗨,Michael,感谢您的回复,我只是想看看 fork() 是如何工作的以及 wait() 是如何工作的。问题是在 gcc 中输出是正确的,而在 xcode 中则不是,为什么会发生这种情况,xcode 会发送中断信号来处理?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-14
    相关资源
    最近更新 更多