【问题标题】:Writing multiple fields (struct) to fifo将多个字段(结构)写入fifo
【发布时间】:2014-01-11 09:07:22
【问题描述】:

我需要将以下结构写入fifo:

struct msg_t {
   int length;
   char* msg;
};

我 malloc 结构和其中的 char*,我这样写: (假设 msg 是变量名) 写(fifo_fd, &msg, sizeof(msg_t));

长度从另一端读取就好了。 字符串不是.. 如何通过一次写入来编写这两个字段? 如果不是,那么两个单独的写入好吗?

谢谢。

【问题讨论】:

  • 为了清楚起见,请包含一些您正在尝试执行的代码!

标签: c linux struct fifo


【解决方案1】:

您是否考虑过使用flexible array members(也解释了here)?见this...所以声明

struct msg_t {
    unsigned length;
    char msg[];
};

用例如分配它

struct msg_t* make_msg(unsigned l) {
  // one extra byte for the terminating null char
  struct msg_t* m = malloc(sizeof(struct msg_t)+l+1; 
  if (!m) { perror("malloc m"); exit(EXIT_FAILURE); };
  memset(m, 0, sizeof(struct msg_t)+l+1);
  m->length = l;
  return m;
}

然后用例如写它

fwrite(m, sizeof(struct msg_t)+m->length+1, 1, fil);

或者如果你使用write 自己做缓冲(因为write 可以是部分的!)例如

void write_msg(int fd, struct msg_t *m) {
   assert(m != NULL);
   char* b = m;
   unsigned siz = sizeof(struct msg_t)+m->length+1);
   while (siz>0) {
      int cnt=write (fd, b, siz);
      if (cnt<0) { perror("write"); exit(EXIT_FAILURE); };
      b += cnt;
      siz -= cnt;
   }
}

【讨论】:

  • 有什么理由使用unsigned 而使用size_t 代替length
【解决方案2】:

您将只写长度和指针地址,我怀疑这是您在另一端想要的。我的猜测是你真正想要的是这样的:

struct msg_t msg;
// Initialise msg
write( fifo_fd, &(msg.length), sizeof(int) );
write( fifo_fd, msg.msg, msg.length );

【讨论】:

  • 谢谢.. 这就是我的想法,但是,我认为有一种方法可以在一次写入中做到这一点。我想这是最正确的方法:)
  • @dlv 有种方法可以一次性完成,但在数据存储方面需要一些准备工作。老实说,如果这就是你想要做的一切,那就不麻烦了。这个答案会做你需要的。 (+1,顺便说一句)。
猜你喜欢
  • 2011-08-30
  • 1970-01-01
  • 2019-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-22
相关资源
最近更新 更多