gpt4 book ai didi

c - Linux 管道和 sigaction

转载 作者:太空宇宙 更新时间:2023-11-04 10:10:17 25 4
gpt4 key购买 nike

我有一些代码可以捕获 SIGIO 信号。我想写一个应用程序,它会被告知数据到达管道。我故意不想使用 select() 函数来做到这一点。这是代码:

void handler (int x)
{
int fd, st;
char buf[32];
printf("signal_entry\n");
fd = open("/tmp/pipe", O_RDWR);
memset(buf, 0, sizeof(buf));
st = read(fd, buf, 32);
printf("st: %d buf: %s\n", st, buf);
close(fd);
printf("signal_exit\n\n");
}

int main (void)
{
int fd, sf, fl, st, num;
struct stat sb;

fd = open("/tmp/pipe", O_RDWR);
memset(&act1, 0, sizeof(act1));
sigfillset(&act1.sa_mask);
act1.sa_handler = handler;
sigaction(SIGIO, &act1, NULL);
sf = fcntl(fd, F_SETOWN, getpid());
fl = fcntl(fd, F_GETFL);
fcntl(fd, F_SETFL, fl | O_ASYNC);
while (1) {
printf("x\n");
sleep(1);
}
}

运行后它每 1 秒显示一次“x”字母。然后我在管道/tmp/pipe 中写入一些东西:

echo "bla" > /tmp/pipe.

程序的 react 是它从管道读取数据(字符串“bla”)并显示其内容——这没问题。

问题是应用程序一次又一次地调用 my SIGIO 处理程序。我的意思是“处理程序”过程被无限调用,因此 main() 过程中的“while”循环不再运行。

为什么会出现这种效果?我错过了什么吗?我认为每次“回声”调用只会调用一次“处理程序”...

最佳答案

在您的 echo 命令终止后,您在“main”中打开的管道是 EOF,因此它将不断触发 SIGIO 事件(即管道上的 EOF)。因此,您必须在 main 函数中重新打开管道才能使其再次运行。

但是,在处理程序中重新打开管道没有任何用处。只需使用 open() 中的 fd - 在 main() 中调用。

关于c - Linux 管道和 sigaction,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49488882/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com