I have a program written in Python that I need to contact from a C++ Program. I'm creating the Pipe Server on the C++ program with the client being in Python. I can't wrap my head around how to properly read/write between the 2 programs as each time I try a different behavior occurs. Note that I want the pipe to remain open for multiple reads/writes into the future.
Server (C++)
#include <windows.h>
#include <iostream>
using namespace std;
#define FGPIPE TEXT("\\\\.\\pipe\\FGChroma")
int main()
{
HANDLE hPipe;
DWORD dwWritten;
DWORD MAX_BUF_SIZE = 8;
hPipe = CreateNamedPipe(FGPIPE,
PIPE_ACCESS_OUTBOUND,
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
2,
MAX_BUF_SIZE*16,
0,
NMPWAIT_USE_DEFAULT_WAIT,
NULL
);
cout<<"Pipe? "<<hPipe<<endl;
cout<<"Awaiting Connection"<<endl;
cout<<ConnectNamedPipe(hPipe, NULL)<<endl;
cout<<"Connected"<<endl;
WriteFile(hPipe, "MSG1\n", 5, &dwWritten, NULL);
WriteFile(hPipe, "MSG2\n", 5, &dwWritten, NULL);
FlushFileBuffers(hPipe);
///Need to Wait for read here
cout<<"Disconnecting"<<endl;
DisconnectNamedPipe(hPipe);
}
Client (Python)
f = open(r"\\.\\pipe\\FGChroma", 'r', 0)
while True:
value = f.read()
print(value)
When I attempt to do the f.read()
in Python, I get an error OSError 22 Invalid Argument, which is fair since I've disconnected the pipe. However if I don't disconnect the pipe then the Python code never finishes reading and keeps waiting until the pipe is closed or disconnected. I feel like the solution is simple and I'm just missing something tiny that's going over my head. I read the Documentation for named pipes and the Win APIs, I also tried win32py and other alternatives and I face the same issue; I don't understand how to keep a connection alive between the 2 instances and allow for reading without having to disconnect, or to wait for reading.