消息队列的代码老是不成功,我是参照《linux网络编程》4.2.4编写的
#include
#include
#include
#include
#include
#include
#include
#include
#include
//显示消息队列属性的函数
void show_msg_attr(int msgid, struct msqid_ds msg_info) {
int ret = -1;
sleep(1);
ret = msgctl(msgid, IPC_STAT, &msg_info);
if(ret == -1) {
puts("获取消息失败");
return ;
}
printf("现在队列中的字节数: %ld\n",msg_info.__msg_cbytes);
printf("消息队列中消息数: %ld\n",msg_info.msg_qnum);
printf("消息队列中最大字节数: %ld\n",msg_info.msg_qbytes);
printf("最后发送消息的进程pid : %d\n",msg_info.msg_lspid);
printf("最后接收消息的进程pid : %d\n",msg_info.msg_lrpid);
printf("最后发送消息的时间 : %ld\n",msg_info.msg_stime);
printf("最后接收消息的时间 : %ld\n",msg_info.msg_rtime);
printf("消息的最后变化时间 : %ld\n",msg_info.msg_ctime);
printf("消息UID是 : %d",msg_info.msg_perm.uid);
printf("消息GID是 : %d",msg_info.msg_perm.gid);
}
int main(int argc, char *argv[]) {
int ret = -1;
int msg_flags, msg_id;key_t key;
struct msgmbuf {
int mtype;
char mtext[20];
};
struct msqid_ds msg_info;
struct msgmbuf msg_buf;
int msg_send_flags, msg_rece_flags;
key = ftok("/home/luoxin/",'b');
if(key == -1) {
puts("建立KEY失败");
return -1;
}
else {
puts("成功建立KEY");
printf("key = 0x%x\n",key);
}
msg_flags = IPC_CREAT ;
msg_id = msgget(key, msg_flags);
if(msg_id == -1) {
puts("消息队列建立失败");
return -1;
}
else {
puts("消息队列建立成功");
printf("msgid = %d\n",msg_id);
}
show_msg_attr(msg_id, msg_info);
msg_send_flags = IPC_NOWAIT;
msg_buf.mtype = 10;
memcpy(msg_buf.mtext, "测试消息", sizeof("测试消息"));
ret = msgsnd(msg_id, &msg_buf, sizeof("测试消息"), msg_send_flags);
if(ret == -1) {
puts("消息发送失败");
return -1;
}
show_msg_attr(msg_id, msg_info);
msg_rece_flags = IPC_NOWAIT | MSG_NOERROR;
memset(msg_buf.mtext,0, 10);
ret = msgrcv(msg_id, &msg_buf, 10, 10, msg_rece_flags);
if(ret == -1) {
puts("接收消息失败");
return -1;
}
else {
printf("接收消息成功,消息为: %s\n",msg_buf.mtext);
}
show_msg_attr(msg_id, msg_info);
}