【问题标题】:Checking if wait() failed检查 wait() 是否失败
【发布时间】:2016-11-20 11:47:41
【问题描述】:

为了知道 wait() 是否有效,像下面这样检查它是否正确?理论上,如果wait()没有失败,应该把结束的子pid返回给父进程,否则父进程会是1,对吧?

switch (process = fork())
{
    case -1:
        // Fork fail
        perror("Fork failed");
        exit(EXIT_FAILURE);

    case 0:
        //Child process
        HERE CODE DOES SOMETHING
        exit(EXIT_SUCCESS);
    default:
        //Parent process 
        pid=wait(&status);

        if(pid==1){
            perror("Wait failed");
        }else{
        exit(EXIT_SUCCESS);
        }
}

【问题讨论】:

  • 阅读函数的文档最有帮助:man7.org/linux/man-pages/man2/waitpid.2.html
  • 除了 wait 在出现错误时返回 -1 而不是 1 的事实(现有答案已涵盖)之外,请考虑使用 waitpid 以确保您正在等待您刚刚完成的过程分叉,而不是碰巧退出的第一个子进程(可能更早分叉,或由另一个线程)。此外,最好调用_exit 而不是exit,以防止无意中刷新子进程继承的父级stdip 缓冲区。
  • @user4815162342 谢谢。

标签: c linux wait waitpid


【解决方案1】:

引用man 2 wait:

返回值

wait():成功时,返回终止子进程的进程ID; 开启 错误,返回-1

所以要检查wait(2) 是否失败,这就足够了:

if (wait(&status) == -1) {
    perror("wait failed");
    exit(1);
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-30
  • 1970-01-01
  • 1970-01-01
  • 2012-04-05
  • 2016-09-17
  • 2019-05-23
  • 2012-07-11
相关资源
最近更新 更多