Noelia Belen Lopez
Noelia Belen Lopez

Reputation: 126

Pass a whole struct in c through a pipe

I need to pass this struct through a pipe:

typedef struct Student {
  char * name;
  char * average;
} Student;

typedef struct Connection {
  int fd;
  int dataSize;
  void * data;
} Connection;

typedef struct Request {    
  int action;
  Connection * connection;
} Request;

My problem is that I don't know how to write the Student struct and how to read it. I can read correctly the fd, action and dataSize, but I could't fix it for the structure. I Hope you can help me. Perhaps there is an easier way to do this and pass the whole entire request structure.

So I did this on the client side: (writeNamedPipe uses write)

requestState writeRequest(Request * request, int fd) {
  writeNamedPipe(fd, &request -> action, sizeof(int));
  writeNamedPipe(fd, &request -> connection -> fd, sizeof(int));
  writeNamedPipe(fd, &request -> connection -> dataSize, sizeof(int));
  writeNamedPipe(fd, &request -> connection -> data, request -> connection -> dataSize);
  return REQUEST_OK;
}

And this in the server side:

Request * getRequest(Connection * connection) {
  Request *request; 
  int action, fd = 0;
  int dataSize;
  void * data;
  read(connection-> fd, &action, sizeof(int));
  read(connection-> fd, &fd, sizeof(int));
  read(connection-> fd, &dataSize, sizeof(int));
  data = malloc (dataSize);
  read(connection-> fd, data, dataSize);
  request = createRequest(action, fd, dataSize, data);
  return request;
}

Upvotes: 1

Views: 2065

Answers (1)

mgagnon
mgagnon

Reputation: 314

The Student struct only contain pointers, so you cannot send the whole struct at once. It would be possible if you had fix array instead of dynamically allocated ones.

example:

struct Student {
    char name[32];
    char average[16];
};

I guess this would probably answers your question:

C - serialization techniques

Upvotes: 1

Related Questions