管道没有这样的文件或目录
Pipe no such file or directory
我正在尝试使用 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
开头,名称后会有一个 |
。
管道将保留在磁盘上是的(尽管 /tmp
通常在重新启动时清空)。
请注意,如果您尝试使用 O_WRONLY
打开文件,但文件 不存在 ,open
将失败并返回 ENOENT
, return 将 -1
作为 fd
。 open
永远不会尝试只用 O_WRONLY
创建一个新文件;要创建新的 常规 文件,您需要调用
open("/tmp/test", O_WRONLY|O_CREAT, 0600);
其中 0600 是文件所需的 mode/permissions。
使用 -1
调用 write
和 close
随后将失败并显示 EBADF
。 请理解您必须始终检查所有系统调用的return值。有时在 Whosebug 示例中,为了简洁起见,它们被省略了,这应该是常识,需要添加检查。
要写一个C++的内容string
,直接从.c_str()
写:
write(fd, wr_string.c_str(), wr_string.length());
还经常检查 C 函数的错误代码; mkfifo
、open
、write
可能会失败,它们 return 一个值 < 0
,您需要准备好处理这些情况。
我正在尝试使用 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
开头,名称后会有一个 |
。
管道将保留在磁盘上是的(尽管 /tmp
通常在重新启动时清空)。
请注意,如果您尝试使用 O_WRONLY
打开文件,但文件 不存在 ,open
将失败并返回 ENOENT
, return 将 -1
作为 fd
。 open
永远不会尝试只用 O_WRONLY
创建一个新文件;要创建新的 常规 文件,您需要调用
open("/tmp/test", O_WRONLY|O_CREAT, 0600);
其中 0600 是文件所需的 mode/permissions。
使用 -1
调用 write
和 close
随后将失败并显示 EBADF
。 请理解您必须始终检查所有系统调用的return值。有时在 Whosebug 示例中,为了简洁起见,它们被省略了,这应该是常识,需要添加检查。
要写一个C++的内容string
,直接从.c_str()
写:
write(fd, wr_string.c_str(), wr_string.length());
还经常检查 C 函数的错误代码; mkfifo
、open
、write
可能会失败,它们 return 一个值 < 0
,您需要准备好处理这些情况。