0
我尝试通过命名管道,在两个进程之间,使用ifstream和ofstream在C++中发送对象。我已经阅读并尝试了很多东西,但是我的研究一无所获。C++:通过命名管道发送对象
我在我的对象序列化期间阻塞。 当我尝试投射并发送到我命名的管道时,我无法将我的对象恢复到其正常状态。
我尝试一些与此代码,但它的命名管道通过后的对象是未满:
#include <string.h>
#include <iostream>
#include <unistd.h>
#include <fstream>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
class Obj {
public:
std::string text1;
std::string text2;
};
int main() {
mkfifo("fifo", 0666);
if (fork() == 0) //Receiving Side
{
std::ifstream fifo("fifo", std::ofstream::binary);
//Re-make the object
Obj *tmp = new Obj();
char *b = new char[sizeof(*tmp)];
//Receive from named pipe
fifo >> b;
//Recover the object
memcpy(&*tmp, b, sizeof(*tmp));
//Display object content
std::cout << tmp->text1 << std::endl << tmp->text2 << std::endl;
//!\ Output = "Some \n" /!\\
fifo.close();
delete tmp;
delete[] b;
}
else //Sending Side
{
std::ofstream fifo("fifo", std::ofstream::binary);
//Create the object
Obj *struct_data = new Obj();
struct_data->text1 = "Some text";
struct_data->text2 = "Some text";
char *b = new char[sizeof(*struct_data)];
//Serialize the object
memcpy((void *)b, &*struct_data, sizeof(*struct_data));
//Send to named pipe
fifo << b;
fifo.close();
wait(NULL);
delete[] b;
}
//delete struct_data;
return (0);
}
是否有人可以给我一个提示或EN例子吗?
谢谢! :)
我们展示的序列化代码。是否记录了字节格式?如果是这样,请告诉我们文档。如果没有,请记录下来。相信我,这是值得努力的文件任何协议 - 理想之前,你编写它。 –
当你说“铸造和发送”......你是实际序列化,还是只是试图发送原始字节?你的物体是什么样的? – Useless
您的问题可能与管道无关(指定或不指定)。您可以尝试让发送者写入标准输出,而阅读器从标准输入接收对象并使用'|'连接它们。节省了很多努力来设置管道,而不是。 –