从fifo中读取阻止

时间:2017-03-11 12:32:38

标签: c named-pipes

我在/ tmp / foo中有一个fifo(命名管道)。 我想从fifo中读取,如果fifo是空的,程序应该睡觉。 目前这是我的解决方案:

char buf [7];
FILE *f = fopen("/tmp/foo", "r");
while(!fgets(buf, 7, f)){
    sleep(1);
}

fgets只会阻塞,直到某些数据写入fifo。但是如果fifo是空的,则fgets不会阻塞。 是否有一个优雅的解决方案只有在数据可用的情 我在Unix(Raspian)上工作

===解===

我用Python解决了它。 @Jonathan Leffler说fopen阻塞是正确的,直到另一个进程打开管道。

问题的解决方法是在阅读后关闭文件并重新打开。 为了防止第二个进程(例如cat)保持打开状态,关闭文件并等待一小段时间就足够了。 这看起来像这样:

while True:
    f = open('/tmp/HA/temp', 'w') #blocks until pipe is opend somewhere else
    f.write("foo") #access file
    f.close() #close it
    time.sleep(0.1) #second programm might end file access

0 个答案:

没有答案
相关问题