当执行以下C程序并将SIGUSR1反复发送到正在运行的进程时,pclose()调用有时会返回13.13对应于我的系统上的SIGPIPE。
为什么会发生这种事?
我正在使用while true; do kill -SIGUSR1 <process-id>; done发送SIGUSR1到程序。该程序在Ubuntu14.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);
}发布于 2014-04-26 07:38:30
当fgets被信号打断时,就会发生这种情况。程序不会将管道读到末尾并关闭它。另一个程序则是SIGPIPE。
正确的管道读取操作是:
do {
while (fgets(b, BUFSIZ, s) != NULL) ;
} while (errno == EINTR);https://stackoverflow.com/questions/23307988
复制相似问题