【问题标题】:wait function in if condition statementif 条件语句中的等待函数
【发布时间】:2016-02-02 03:42:49
【问题描述】:

在下面的代码中,

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main (void) {
   pid_t childpid;
   childpid = fork();
   if (childpid == -1) {
   /* set up signal handlers here ... */
      perror("Failed to fork");
      return 1;
   }
   if (childpid == 0)
      fprintf(stderr, "I am child %ld\n", (long)getpid());
   else if (wait(NULL) != childpid)
      fprintf(stderr, "A signal must have interrupted the wait!\n");
   else
      fprintf(stderr, "I am parent %ld with child %ld\n", (long)getpid(),
           (long)childpid);
   return 0;
}

多重 if else 语句的行为如何?如果子进程没有立即返回,else if语句中的条件是否总是为假,然后执行else语句?

【问题讨论】:

  • 计算机将评估wait(NULL) != childpid,然后才能知道是执行第二个还是第三个fprintf。在wait 返回之前,这不会完成。

标签: c unix wait


【解决方案1】:

如果子进程没有立即返回,else if语句中的条件是否总是为假,然后执行else语句?

wait 的调用是阻塞调用。它会一直阻塞,直到孩子的状态改变或被信号中断。

来自http://linux.die.net/man/2/wait

状态改变被认为是:孩子终止;孩子被信号拦住;或者孩子被信号恢复了。

否则它们会阻塞直到子进程改变状态或信号处理程序中断调用

【讨论】:

    猜你喜欢
    • 2023-01-20
    • 2018-07-08
    • 2013-08-04
    • 1970-01-01
    • 2021-03-02
    • 2016-05-27
    • 2013-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多