管道没有这样的文件或目录

Pipe no such file or directory

本文关键字:文件 管道      更新时间:2023-10-16

我正试图用C++创建一个命名管道,并在python上读取它。这是我的代码:

const int MAX_BUF = 1024;
string wr_string = "Hi.";
char text[MAX_BUF] = "";
strcpy(text, wr_string.c_str());
int fd = open("/tmp/test", O_WRONLY);   // Open the pipe
write(fd,text,MAX_BUF);              // Write
close(fd);                                  // Close the pipe - allow the read

我是这样读的:

import os
import time
pipe = open("/tmp/OKC_avgprice", "r")
line = pipe.read() 
pipe.close()   
print line

然而,每次我试图阅读它时,我都会得到:

Traceback (most recent call last):
File "ipc.py", line 4, in <module>
pipe = open("/tmp/test", "r")
IOError: [Errno 2] No such file or directory: '/tmp/test'

写入管道时应自动创建否?为什么没有找到?

谢谢!

您的C++代码没有创建命名管道;必须首先使用mkfifo(3):创建命名管道

mkfifo("/tmp/test", 0600) // 0600 means writable and readable by owner only

这样的fifo将作为出现在ls -laF(GNU)上

prw-------  1 user  group     0 Apr 12 07:02 test|

值得注意的是,该行将以p开头,并且名称后面将有一个|。管道将保留在磁盘上yes(尽管/tmp通常在重新启动时清空)。


请注意,如果尝试使用O_WRONLY打开文件,但文件不存在,则open将使用ENOENT失败,返回-1作为fd。CCD_ 11将永远不会尝试创建仅具有CCD_ 12的新文件;要创建一个新的常规文件,您需要调用

open("/tmp/test", O_WRONLY|O_CREAT, 0600);

其中0600是文件所需的模式/权限。

-1调用writeclose随后将用EBADF失败请理解您必须始终检查所有系统调用的返回值。有时在Stackoverflow示例中,为了简洁起见,它们被省略了,应该知道需要添加检查。


要写入C++string的内容,请直接从.c_str():写入

write(fd, wr_string.c_str(), wr_string.length());

还要始终检查来自C函数的错误代码;mkfifoopenwrite可能会失败,并且它们返回值< 0,您需要做好处理这些情况的准备。