在C++和 Python 程序中使用命名管道的 IPC 挂起
IPC using Named Pipes in C++ and Python program hangs
我正在通过在Unix上使用命名管道来练习IPC,并尝试使用python在FIFO文件中写入字符串并通过C++程序反转它。但是Python中的程序被挂起并且没有返回任何结果。
用于写入文件的 Python 代码:
import os
path= "/home/myProgram"
os.mkfifo(path)
fifo=open(path,'w')
string=input("Enter String to be reversed:t ")
fifo.write(string)
fifo.close()
程序挂起,不在此处要求任何输入。 当我爆发时,我收到以下错误:
Traceback (most recent call last):
File "writer.py", line 4, in <module>
fifo=open(path,'w')
KeyboardInterrupt
C++用于读取文件的代码:
#include <fcntl.h>
#include <iostream>
#include <sys/stat.h>
#include <unistd.h>
#include <string>
#include <string.h>
#define MAX_BUF 1024
using namespace std;
char* strrev(char *str){
int i = strlen(str)-1,j=0;
char ch;
while(i>j)
{
ch = str[i];
str[i]= str[j];
str[j] = ch;
i--;
j++;
}
return str;
}
int main()
{
int fd;
char *myfifo = "/home/myProgram";
char buf[MAX_BUF];
/* open, read, and display the message from the FIFO */
fd = open(myfifo, O_RDONLY);
read(fd, buf, MAX_BUF);
cout<<"Received:"<< buf<<endl;
cout<<"The reversed string is n"<<strrev(buf)<<endl;
close(fd);
return 0;
}
因为,编写器程序无法执行,无法测试读取器代码,因此无法在此处提及结果。
请帮忙。
> python 代码块在open()
. 它正在等待读者。
通常可以切换到非阻塞并使用os.open()
。 使用FIFO,你会得到一个错误,ENXIO。 这基本上等同于没有读者在场。
因此,先进先出的"所有者"应该是读者。 这条规则可能只是一个风格问题。 我不知道这种限制的具体原因。
下面是一些 python 代码,演示了交错多个读取器和编写器。
import os
r1 = os.open('myfifo', os.OS_RDONLY | os.OS_NONBLOCK)
r2 = os.open('myfifo', os.OS_RDONLY | os.OS_NONBLOCK)
w1 = os.open('myfifo', os.OS_WRONLY | os.OS_NONBLOCK)
w2 = os.open('myfifo', os.OS_WRONLY | os.OS_NONBLOCK)
os.write(w1, b'hello')
msg = os.read(r1, 100)
print(msg.decode())
os.write(w2, b'hello')
msg = os.read(r2, 100)
相关文章:
- 挂起和取消挂起一个文件DLL
- 如何防止C++遗留代码中的挂起指针
- 为什么所有C++编译器都会崩溃或挂起此代码
- 我编写了代码将十进制分数转换为其二进制等效数.它编译得很好,但在执行时挂起
- 构建挂起,即使是适度的文件大小
- 循环挂起迭代的 std::擦除 on std::list
- Poco::Net::FTPClientSession 在 open() 方法上挂起 129 秒,如果 ftp 主机不存
- Node.js fs.open() 在尝试打开 4 个以上的命名管道 (FIFO) 后挂起
- 从不同进程中的另一个线程挂起/恢复线程或进程
- Boost (Beast) websocket:同步写入挂起
- 为什么析构函数挂起
- 使用互斥会挂起程序
- 在C++和 Python 程序中使用命名管道的 IPC 挂起
- 设置变量时C++程序挂起
- 第一次尝试使用new动态创建结构数组,程序挂起没有错误
- 在两个子进程之间管道时,C++ 进程挂起
- 启动子进程时的争用条件导致从管道读取挂起
- 尝试使用 execp、dup2 和管道实现 shell,挂起或"bad file descriptor"
- ReadFile(客户端命名管道)挂起-Win32 VC++
- 无法从挂起进程的独立线程中的管道中读取