Zohair Abbas Hadi
Zohair Abbas Hadi

Reputation: 123

Object passing using Pipes in C++

class Proc
{
public:
    string schedulingAlgo;
    string procName;
    int quantum;
    int arrivalTime;
    int burstTime;
}

This is my class whose object i want to pass to another process using pipes using the write sys call

write(fd_admit_write,(char*)&procs, sizeof((char*)&procs));

And in the other process, I am trying to read this and convert it back into the Proc type using this

char buffer[15];
read(fd_admit_read,buffer,15);
Proc *pp = reinterpret_cast<Proc *>(buffer);

I know that the method I used for conversion is fine because I tried it independently but when I use it in pipes, the output of pp gets distorted.

Upvotes: 0

Views: 759

Answers (1)

sparik
sparik

Reputation: 1201

Processes do not share memory (generally). They do not see each others' memory. That is, you cannot have a pointer to a memory address in another process.

As far as I understand, you are sending a Proc* to another process. While Proc* points to a valid Proc object in the sending process, it will point to uninitialized memory in the receiving process. You have to actually send all the data needed for constructing a Proc object, and construct it on the receiver side.

Even if you sent the Proc object itself instead of a pointer to it, it would not work, because it has a string member variable, and a string contains a pointer to its data (except in case of small string optimization).

You can use a good binary protocol like msgpack or implement your own serialization/deserialization based on your needs.

Upvotes: 1

Related Questions