SIGCHLD在父进程中导致EOF

时间:2018-11-23 17:43:36

标签: c linux process signals fork

一个简单的程序示例

  • 通过getchar逐字符读取char,直到EOF
  • 遇到“ a”时启动子进程。

奇怪的是,安装信号处理程序会使getchar每当孩子退出时都返回EOF。相当有害的副作用。

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>

void handler() {
    // 
}

void action() {
    if (fork() == 0) {
        printf("(action)\n");
        sleep(1);
        exit(0);
    }
}

int main(int argc, char** argv) {
    char c;
    signal(SIGCHLD, handler);                // signal
    while (EOF != (c = getchar())) {
        if (c == 'a') action();
    }
    printf("End Of Data\n");
}

注释掉信号ligne后,问题消失了。 有人可以解释为什么会这样吗?

似乎与Handling SIGCHLD will return EOF to the father, why?相同的问题 关于为什么以及如何避免这种情况尚无明确答案。


编辑1:对我来说不清楚(星期五晚上...)

  • 原因是getchar()下的系统调用被中断,导致它返回EOF(如手册页中所述)。
  • (临时)解决方案:检查errno中是否有EINTR

在此示例中

 while (EOF != (c = getchar()) || errno == EINTR) {

编辑2:检查errno适用于getchar(),但不能使您getline()步步高升。

真正的解决方案是忘记过时的signal(),而将sigaction()SA_RESTART标志一起使用。

0 个答案:

没有答案
相关问题