Linux pclose()间歇返回SIGPIPE

Linux pclose()间歇返回SIGPIPE,linux,multithreading,signals,posix,popen,Linux,Multithreading,Signals,Posix,Popen,当执行以下C程序,并且反复将SIGUSR1发送到正在运行的进程时,pclose()调用有时会返回13。13对应于我的系统上的SIGPIPE 为什么会发生这种情况? 我正在使用而不是true;杀死-SIGUSR1;完成向程序发送SIGUSR1。该程序在Ubuntu 14.04上执行 #include <pthread.h> #include <signal.h> #include <unistd.h> #include <stdio.h> void

当执行以下C程序,并且反复将
SIGUSR1
发送到正在运行的进程时,
pclose()
调用有时会返回13。13对应于我的系统上的
SIGPIPE

为什么会发生这种情况?

我正在使用
而不是true;杀死-SIGUSR1;完成
向程序发送
SIGUSR1
。该程序在Ubuntu 14.04上执行

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

void handler(int i) {}

void* task(void*)
{
    FILE *s;
    char b [BUFSIZ];
    while (1) {
        if ((s = popen("echo hello", "r")) == NULL) {
            printf("popen() failed\n");
        }
        while (fgets(b, BUFSIZ, s) != NULL) ;
        if (int r = pclose(s)) {
            printf("pclose() failed (%d)\n", r);
        }
    }

    return 0;
}

int main(int argc, char **argv)
{
    struct sigaction action;
    action.sa_handler = handler;
    sigemptyset(&action.sa_mask);
    action.sa_flags = 0;
    sigaction(SIGUSR1, &action, NULL);

    pthread_t tid;
    pthread_create(&tid, 0, task, NULL);
    pthread_join(tid, NULL);
}
#包括
#包括
#包括
#包括
无效处理程序(int i){}
void*任务(void*)
{
文件*s;
字符b[BUFSIZ];
而(1){
if((s=popen(“echo hello”,“r”))==NULL){
printf(“popen()失败\n”);
}
while(fgets(b,BUFSIZ,s)!=NULL);
如果(int r=pclose){
printf(“pclose()失败(%d)\n”,r);
}
}
返回0;
}
int main(int argc,字符**argv)
{
结构动作;
action.sa_handler=处理程序;
sigemptyset(和action.sa_mask);
action.sa_标志=0;
sigaction(SIGUSR1,&action,NULL);
pthread_t tid;
pthread_create(&tid,0,task,NULL);
pthread_join(tid,NULL);
}

当信号中断fgets时,会发生这种情况。程序不会将管道读到底并将其关闭。另一个程序则是SIGPIPEs

正确的管道读数操作是:

 do {
    while (fgets(b, BUFSIZ, s) != NULL) ;
 } while (errno == EINTR);

谢谢我应该已经阅读了
fgets()
文档closer:“成功完成后,fgets()将返回s。如果流位于文件结尾,则应设置流的文件结尾指示符,fgets()将返回空指针。如果发生读取错误,则应设置流的错误指示符,fgets()应返回空指针,并应设置errno以指示错误。“