通过linux消息队列传递的C结构间歇性失败
我有一个客户端进程,它构建了一个IPC消息结构队列,该队列通过linux IPC消息队列发送到服务器。大小为68字节。结构定义为:通过linux消息队列传递的C结构间歇性失败,c,linux,ipc,message,C,Linux,Ipc,Message,我有一个客户端进程,它构建了一个IPC消息结构队列,该队列通过linux IPC消息队列发送到服务器。大小为68字节。结构定义为: struct FOO_TYPE { long mtype; struct { int sev; char msg[32]; char bt[32]; } foomsg; }; 客户端在函数和mallocs空间中本地声明一个指向FOO_类型的结构的指针。然后,代码加载sev、msg和bt字段 static str
struct FOO_TYPE {
long mtype;
struct {
int sev;
char msg[32];
char bt[32];
} foomsg;
};
客户端在函数和mallocs空间中本地声明一个指向FOO_类型的结构的指针。然后,代码加载sev、msg和bt字段
static struct FOO_TYPE *FooEntry = NULL;
…代码剪辑
if (FooEntry == NULL)
FooEntry = malloc(sizeof(struct FOO_TYPE));
memset(FooEntry, 0, sizeof(struct FOO_TYPE));
MsgSize = sizeof(FooEntry) - sizeof(long);
FooEntry->mtype = CHANGESTATUS;
FooEntry->foomsg.sev = serr->serr_data->sev;
strcpy(FooEntry->syserrmsg.emsg, elog);
strcpy(FooEntry->syserrmsg.bt, btlog);
result = msg_snd(FooExchange, FooEntry, MsgSize, IPC_WAIT);
…代码剪辑
if (FooEntry == NULL)
FooEntry = malloc(sizeof(struct FOO_TYPE));
memset(FooEntry, 0, sizeof(struct FOO_TYPE));
MsgSize = sizeof(FooEntry) - sizeof(long);
FooEntry->mtype = CHANGESTATUS;
FooEntry->foomsg.sev = serr->serr_data->sev;
strcpy(FooEntry->syserrmsg.emsg, elog);
strcpy(FooEntry->syserrmsg.bt, btlog);
result = msg_snd(FooExchange, FooEntry, MsgSize, IPC_WAIT);
。。。代码剪辑
if (FooEntry == NULL)
FooEntry = malloc(sizeof(struct FOO_TYPE));
memset(FooEntry, 0, sizeof(struct FOO_TYPE));
MsgSize = sizeof(FooEntry) - sizeof(long);
FooEntry->mtype = CHANGESTATUS;
FooEntry->foomsg.sev = serr->serr_data->sev;
strcpy(FooEntry->syserrmsg.emsg, elog);
strcpy(FooEntry->syserrmsg.bt, btlog);
result = msg_snd(FooExchange, FooEntry, MsgSize, IPC_WAIT);
接收IPC消息的服务器将获得68个字节(即:sizeof FOO_TYPE),但其中的字段时断时续地丢失或是垃圾
我是否也必须为结构内部的结构中的字段分配malloc空间???这至少是一个错误:
MsgSize = sizeof(FooEntry) - sizeof(long);
FooEntry
是此处定义的指针:
static struct FOO_TYPE *FooEntry = NULL;
因此sizeof(FooEntry)
提供指针的大小,而不是结构的大小
你可能想要
MsgSize = sizeof(*FooEntry) - sizeof(long);
或者只是
MsgSize = sizeof(FooEntry->foomsg);
如果指针只有malloc空间,则会出现问题。。。但是发布代码来描述代码我们无法判断代码未发布时的问题所在。另外请注意。。。两个系统上的结构填充可能不同。当为IPC使用结构时,你应该使用压缩结构。如果你在史前机器上,你的结构大于68字节。字符+整数+长字符为64字节。而且,正如所指出的,可能会涉及填充。代码段会按要求添加到post中。机器正在运行RHEL 7.9-64位.yep。这是一个错误。谢谢。