gpt4 book ai didi

C++ : Send an object through a named pipe

转载 作者:行者123 更新时间:2023-11-30 03:42:46 24 4
gpt4 key购买 nike

我尝试在 C++ 中使用 ifstream 和 ofstream 在两个进程之间通过命名管道发送对象。我已经阅读并尝试了很多东西,但我的研究一无所获。

我在我的对象序列化期间阻塞。当我尝试转换并发送到我的命名管道时,我无法将我的对象恢复到正常状态。

我尝试使用此代码进行一些操作,但对象在通过命名管道后还未满:

#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);
}

有人可以给我提示或示例吗?

谢谢! :)

最佳答案

您需要正确序列化您的对象。像这样(只做了一个成员,剩下的留给读者作为练习):

#include <iostream>
#include <fstream>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>

class Obj
{
public:
std::string text1;
std::string text2;

friend std::ostream& operator<<(std::ostream &os, const Obj& o);
friend std::istream& operator>>(std::istream &os, Obj& o);
};

std::ostream& operator<<(std::ostream &os, const Obj& o)
{
os << o.text1.length();
os << o.text1;
return os;
}

std::istream& operator>>(std::istream &is, Obj& o)
{
size_t length;
is >> length;
char* tmp = new char[length];
is.get(tmp, length+1);
o.text1 = tmp;
delete[] tmp;
return is;
}

static const char* myfifo = "myfifo";

int main(int argc, char *argv[])
{
mkfifo(myfifo, 0666);

if (argc > 1)
{
std::ifstream infifo(myfifo, std::ifstream::binary);

Obj *tmp = new Obj();

infifo >> *tmp;
infifo.close();

std::cout << "Done reading : [" << tmp->text1 << "]" << std::endl;
}
else
{
std::ofstream outfifo(myfifo, std::ofstream::binary);

Obj *struct_data = new Obj();
struct_data->text1 = "Some text1";
struct_data->text2 = "Some text2";

outfifo << *struct_data;
}
return 0;
}

有关序列化的更多信息,请参阅 https://stackoverflow.com/a/26337239/2742863

关于C++ : Send an object through a named pipe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36644682/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com