send struct in mq_send

百般思念 提交于 2019-11-28 03:08:06

问题


I am using POSIX IPC and according to the documentation - http://man7.org/linux/man-pages/man3/mq_send.3.html

mq_send() method only sends char* data and mq_recv() recieves only character data. However, I want to send a custom struct to my msg queue and on the receiving end, I want to get the struct.

sample struct:

struc Req
{
  pid_t pid;
  char data[4096];
}

So, does anyone know how to accomplish this in C lang?


回答1:


You just need to pass the address of the struct and cast it to the appropriate pointer type: const char * for mq_send and char * for mq_receive.

typedef struct Req
{
  pid_t pid;
  char data[4096];
} Req;

Req buf;

n = mq_receive(mqdes0, (char *) &buf, sizeof(buf), NULL);

mq_send(mqdes1, (const char *) &buf, sizeof(buf), 0);



回答2:


You can use memcpy as follows:

char * data; //Do appropriate allocation.

memcpy(data, &req, sizeof(req)));

On receiving you copy back received data into struct.

memcpy(&rec, data, sizeof(rec)));


来源:https://stackoverflow.com/questions/23044963/send-struct-in-mq-send

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!