当你停止阅读程序时,作者将收到
SIGPIPE
当它试图写入管道时发出信号。此信号的默认配置是终止进程。
如果要检测这种情况,请使用
signal()
或
sigaction()
改变性情
SIG_IGN
.然后写信给管道将报告
EPIPE
错误
此外,不应每次通过回路时都关闭和重新打开管道。开始时打开一次,结束时关闭。关闭管道会导致读卡器出现EOF,之后它将无法读取任何内容。
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
int main()
{
int fd;
// FIFO file path
char * myfifo = "/tmp/myfifo";
// Creating the named file(FIFO)
// mkfifo(<pathname>, <permission>)
mkfifo(myfifo, 0666);
// Open FIFO for write only
fd = open(myfifo, O_WRONLY);
signal(SIGPIPE, SIG_IGN);
char arr1[80];
while (1)
{
// Take an input from user.
fgets(arr1, 80, stdin);
// Write the input on FIFO
// and close it
int res = write(fd, arr1, strlen(arr1)+1);
if (res < 0) {
perror("write");
break;
}
}
close(fd);
return 0;
}
当您停止编写程序时,当读卡器尝试从管道中读取时,它将获得EOF。什么时候
f.readline()
到达EOF时,它返回一个空字符串。你的Python脚本没有检查这一点,所以它会无限循环。
将读卡器更改为:
with open("/tmp/myfifo") as f:
while True:
line = f.readline()
if not line:
break
print(line, end = "")
当管道闭合时,回路将终止。