【发布时间】:2021-10-21 17:57:13
【问题描述】:
当我调用open("./fifo",O_RDONLY) 时,系统调用将阻塞,因为没有人在写入先进先出器./fifo。如果在此期间接收到没有信号处理程序的信号,则该过程立即结束。到现在为止还挺好。
但是当接收到具有信号处理程序的信号时,会执行信号处理程序并且open() 系统调用仍处于阻塞状态。
如何让open() 收到信号后返回?
我试图阻止信号,但它不起作用,因为 open() 没有 sigmask 参数,就像 pselect() 一样。使用O_NONBLOCK 也不起作用,因为无论是否有信号,open() 都会返回错误。删除信号处理程序也不好,因为我希望能够对信号做出反应。
我的测试代码:
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
static volatile bool end=0;
static void catchSignal(int signal)
{
(void)signal;
const char *s="Catched Signal\n";
write(STDERR_FILENO,s,strlen(s));
end=1;
}
static int openFile(void)
{
int fd=open("./in",O_RDONLY);
if(fd<0)
{
perror("can't open file");
exit(1);
}
return fd;
}
int main()
{
if(SIG_ERR==signal(SIGTERM,catchSignal))
{
perror("cant set up signal handler");
return -1;
}
int fd = openFile();
while(end==0)
{
puts("Still running");
usleep(300UL*1000);
}
puts("End now");
if(fd>0)
{
close(fd);
}
return 0;
}
【问题讨论】: