【发布时间】:2015-09-16 10:41:17
【问题描述】:
我正在使用 Namedpipes 通信 (C++) 在两个进程之间传输数据。为了方便起见,我使用 wstring 传输数据,传输结束时一切正常。我无法在接收端接收总数据。 以下是传输结束代码。
wstringstream send_data;
send_data << "10" << " " << "20" << " " << "30" << " " << "40" << " " << "50" << " " << "60" << "\0" ;
DWORD numBytesWritten = 0;
result = WriteFile(
pipe, // handle to our outbound pipe
send_data.str().c_str(), // data to send
send_data.str().size(), // length of data to send (bytes)
&numBytesWritten, // will store actual amount of data sent
NULL // not using overlapped IO
);
以下是接收端代码。
wchar_t buffer[128];
DWORD numBytesRead = 0;
BOOL result = ReadFile(
pipe,
buffer, // the data from the pipe will be put here
127 * sizeof(wchar_t), // number of bytes allocated
&numBytesRead, // this will store number of bytes actually read
NULL // not using overlapped IO
);
if (result) {
buffer[numBytesRead / sizeof(wchar_t)] = '\0'; // null terminate the string
wcout << "Number of bytes read: " << numBytesRead << endl;
wcout << "Message: " << buffer << endl;
}
缓冲区中的结果只包含 10 20 30 有人可以解释一下为什么数据被截断。
【问题讨论】:
-
您确定数据被截断了吗?您似乎没有检查管道以查看是否有任何剩余内容等待读取。你似乎也没有检查你写的字节数是否和你认为写的一样多。
-
从某个流中读取,你不应该期望得到一定的大小(它可能更小甚至为零)。对一些错误或 eof 条件做出反应
-
不应该
send_data.str().size()是send_data.str().size() * sizeof(wchar_t) / sizeof(char),因为您发送的是多字节字符? -
@Hurkyl:是的,我在传输之前确实检查过,wstringstream 中的数据包含什么。所有数据似乎都存在。如果,我没记错的话,“缓冲区”应该打印管道包含的所有数据。
-
@NathanOliver:哇!不错的一个.. 现在,我得到了整个数据。非常感谢
标签: c++ named-pipes wchar-t wstring