首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >pclose()间歇返回SIGPIPE

pclose()间歇返回SIGPIPE
EN

Stack Overflow用户
提问于 2014-04-26 07:22:49
回答 1查看 512关注 0票数 0

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

为什么会发生这种事?

我正在使用while true; do kill -SIGUSR1 <process-id>; done发送SIGUSR1到程序。该程序在Ubuntu14.04上执行。

代码语言:javascript
复制
#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);
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-04-26 07:38:30

fgets被信号打断时,就会发生这种情况。程序不会将管道读到末尾并关闭它。另一个程序则是SIGPIPE。

正确的管道读取操作是:

代码语言:javascript
复制
 do {
    while (fgets(b, BUFSIZ, s) != NULL) ;
 } while (errno == EINTR);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23307988

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档