【问题标题】:Pass a whole struct in c through a pipe通过管道传递 c 中的整个结构
【发布时间】:2016-05-14 20:36:45
【问题描述】:

我需要通过管道传递这个结构:

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;

我的问题是我不知道如何编写 Student 结构以及如何阅读它。我可以正确读取 fd、action 和 dataSize,但我无法为结构修复它。我希望你能帮助我。也许有一种更简单的方法可以做到这一点并传递整个请求结构。

所以我在客户端做了这个: (writeNamedPipe 使用 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;
}

这在服务器端:

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

【问题讨论】:

    标签: c struct pipe


    【解决方案1】:

    Student 结构仅包含指针,因此您不能一次发送整个结构。如果您有固定数组而不是动态分配的数组,那将是可能的。

    示例:

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

    我想这可能会回答你的问题:

    C - serialization techniques

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-27
      • 2013-05-12
      • 2011-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多