Py学习  »  Python

C到Python管道-如何检测读卡器访问

Noel • 3 年前 • 1298 次点击  

我正在用一个C程序向一个命名管道写入数据,用Python程序读取数据。

如果我停止Python程序(reader),那么编写器将自行停止,尽管这是一个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社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/131998
 
1298 次点击  
文章 [ 1 ]  |  最新文章 3 年前
Barmar
Reply   •   1 楼
Barmar    4 年前

当你停止阅读程序时,作者将收到 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 = "")

当管道闭合时,回路将终止。