c - 将 "complex"结构写入 FIFO

标签 c arrays pointers fifo

我正在用 C 语言与客户端服务器一起实现一种“餐厅”实现。 我正在尝试通过 FIFO 发送以下结构:

   typedef struct { 
   int numtable;            //table number to send answer
   char timestamp[20];      //simple timestamp
   int order[MENUSZ];       //array of int with dish IDs
   } request;

关于这个结构,我基本上将表号发送到服务器,通过模板、时间戳“构建”客户端 FIFO 名称,而 order 是一个简单的数组,其中填充了随机选择的整数,以“创建”某种随机菜单请求。 通过此设置,我没有遇到任何问题,使用

   write(server_fd, &request, sizeof(request))

当我想转换指针中的数组顺序[MENUSZ]以创建动态数组时遇到问题,如下所示:

    typedef struct {    
   int numtable;            
   char timestamp[20];      
   int *order;      
   } request;

更改结构后,我使用 malloc 函数为数组分配足够的空间:

   request->order = malloc(sizeof(int)*numclients+1);

数组已正确填充,但由于某种原因,在我添加此指针后,服务器无法从 FIFO 读取数据

   read(server_fd, &request, sizeof(request));

我不明白为什么它不适用于此指针。难道我做错了什么?

最佳答案

The array is fullfilled correctly, but for some reason the server can't read from the FIFO after I added this pointer, by doing

read(server_fd, &request, sizeof(request));

您正在传输包含指针的结构,并且指针的将被正确传输,但它不会指向目标进程中的有效地址,也不会存在内存分配在指针指向的位置。

因此,您需要单独传输数组并在目标进程中重新创建指针,如下所示:

read(server_fd, &request, sizeof(request));

/* allocate memory for request->order in the reader process */
request->order = malloc(sizeof(int)*numclients+1);
read(server_fd, request->order, sizeof(int)*numclients+1);

更好的解决方案是在结构内部传输数组的大小。

在发送端,您需要发送结构和数组内容,类似于

write(server_fd, &request, sizeof(request))
write(server_fd, request->order, sizeof(int)*numclients+1));

关于c - 将 "complex"结构写入 FIFO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26235345/

相关文章:

c - 为什么我们不在 TCP 程序中使用客户端地址?

javascript - 根据不同的概率获取数组的随机项?

const char const *char[] 编译器警告

python - 在 Python 中从多个文本文件中查找并提取字符串

c - C中指向特定地址的指针

c - free/=NULL 是否足以清除内存,还是应该将 SecureZeroMemory 放置在其前面?

c - 将数组与结构一起使用

c - 使用 fprintf 写出一个数组

c - 用0-99的随机数填充C中的二维数组,然后按降序排序

c - 减去指针 p - (p - 1) 如何造成整数溢出?