【发布时间】:2016-04-15 10:28:51
【问题描述】:
我尝试通过命名管道在两个进程之间使用 ifstream 和 ofstream 在 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);
}
有人可以给我一个提示或示例吗?
谢谢! :)
【问题讨论】:
-
向我们展示序列化代码。是否记录了字节格式?如果是这样,请向我们展示文档。如果没有,请记录下来。相信我,记录任何协议都是值得的——最好是在编写代码之前。
-
当你说“cast and send”时......你实际上是在序列化,还是只是试图发送原始字节?你的对象是什么样的?
-
您的问题可能与管道(命名或未命名)无关。您可以尝试让发送者写入标准输出,而阅读者从标准输入接收对象并将它们与
|连接。节省了很多精力来设置管道等等。 -
@Bross 没有序列化对象的代码!
标签: c++ serialization casting named-pipes fifo