Is it possible to prevent application from hanging when both stdin and stdout are connected to named pipes?

孤者浪人 提交于 2020-05-13 21:00:32

问题


Consider the following simple C program, which I will compile to a program called "A":

#include <stdio.h>

int main(int argc, char** argv){
  putchar('C');
  putchar('\n');
}

Now, consider the following bash script:

#!/bin/bash

mkfifo Output1.pipe
mkfifo Output2.pipe

stdbuf -i0 -o0 -e0 ./A > Output1.pipe  &
stdbuf -i0 -o0 -e0 ./A > Output2.pipe  &

cat Output1.pipe
cat Output2.pipe

The output of this script is C\nC. So far everything is fine. Now let's consider the following modification the bash script, observing that the C program never reads stdin.

#!/bin/bash

mkfifo Input1.pipe
mkfifo Input2.pipe

mkfifo Output1.pipe
mkfifo Output2.pipe

stdbuf -i0 -o0 -e0 ./A > Output1.pipe < Input1.pipe &
stdbuf -i0 -o0 -e0 ./A > Output2.pipe < Input2.pipe &

cat Output1.pipe
cat Output2.pipe

When this bash script is run, it hangs until output is manually written to Input1.pipe and then Input2.pipe.

What is going on here and is there a way to get it to not hang at this step?


回答1:


In this setup, your program doesn't even run (AFAIR), because the shell first opens both channels and then the program is started. And opening a reading FIFO hangs until it is opened writing as well.

There is no (easy) way to prevent this.



来源:https://stackoverflow.com/questions/61767692/is-it-possible-to-prevent-application-from-hanging-when-both-stdin-and-stdout-ar

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