【发布时间】:2021-05-07 22:18:03
【问题描述】:
我正在使用 C 程序写入命名管道,并使用 Python 程序读取它。
如果我停止 Python 程序(阅读器),那么编写器会自行停止,尽管这是在 while(1) 循环中。为什么会这样?是无声的崩溃吗?
第二个问题,如果我想检测阅读器何时断开连接,我应该怎么做。我的理想方案是检测断开连接然后继续空闲(即停止发送任何内容)并在阅读器返回后恢复。
下面的玩具代码。
作家(C):
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
int fd;
// FIFO file path
char * myfifo = "/tmp/myfifo";
// Creating the named file(FIFO)
// mkfifo(<pathname>, <permission>)
mkfifo(myfifo, 0666);
char arr1[80];
while (1)
{
// Open FIFO for write only
fd = open(myfifo, O_WRONLY);
// Take an input from user.
fgets(arr1, 80, stdin);
// Write the input on FIFO
// and close it
write(fd, arr1, strlen(arr1)+1);
close(fd);
}
return 0;
}
阅读器(Python)
f = open("/tmp/myfifo")
while 1:
print(f.readline(), end = "")
f.close()
【问题讨论】:
标签: python c named-pipes