FIFO pipe only reads after write end has closed

时光总嘲笑我的痴心妄想 提交于 2019-12-19 10:40:09

问题


I'm trying to create a FIFO pipe between a python file and C file, but the issue is that when reading in the input from the C file, getline blocks until the writer end (in the python file) closes.

C file:

char fifo_emg[] = "emg";
mkfifo(fifo_emg, S_IRWXU);

int fd_emg = open(fifo_emg, O_RDONLY);
FILE* fp = fdopen(fd_emg, "r");

char *line = NULL;
size_t len = 0;
ssize_t _read;
printf("Both ends open. Reading commands...\n");
while ((_read = getline(&line, &len, fp)) != -1) {
    printf("Comamnd: %s", line);
}   

Python file:

fifo = open("emg", "w");

while 1:
    line = raw_input("ENTER COMMAND: ")
    if line[0] == '!':
        break
    else:
        fifo.write(line + '\n')

fifo.close()

When i run both, I want the output from the C file to go "Command: foo" as soon as it is entered through the python input. However, data is only read in when fifo.close() is called, and it is just read in all at once. This is not really helpful since I want a constant stream of commands.


回答1:


Your problem comes from the buffer. FIFO use block buffer by default. So the c program won't read anything until the write buffer of the fifo in python was full. And there's two way to change this behaviour:

  • specify the buffer mode:

there's three buffer mode:

  1. block buffer(default)
  2. line buffer
  3. no buffer at all

What meet your needs here is the line buffer, so use fifo = open("emg", "w", 1); instead of fifo = open("emg", "w"); will fix. number 1 here instead line buffer. python doc

  • another method is force flush the buffer, use fifo.flush after the write operation.



回答2:


yes ..forcing a flush will resolve the issue.




回答3:


As immibis says in the comments, fifo.flush() solved my issue!



来源:https://stackoverflow.com/questions/34411623/fifo-pipe-only-reads-after-write-end-has-closed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!