Linux中用C的msgget()不使用IPC_EXCL也返回EEXIST错误,网上都说不使用IPC_EXCL,光使用IPC_CREAT会返回msgid或创建一个新的队列,
但是,在我的程序里面,并!没!有!
求助大神们帮我看看怎么回事的!
我是在centos6.5中运行的,用的GCC编译
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <errno.h>
void msg_show_attr(int msg_id, struct msqid_ds msg_info){
int ret = -1;
sleep(1);
ret = msgctl(msg_id, IPC_STAT, &msg_info);
if(ret == -1){
printf("failed to get msg info!\n");
return;
}
printf("--------now print info:---------\n");
printf("队列中字节数:%ld\n", msg_info.msg_cbytes);
printf("队列中消息数:%d\n", (int)msg_info.msg_qnum);
printf("队列中最大字节数:%d\n", (int)msg_info.msg_qbytes);
printf("最后发送(接收)消息的进程:%d(%d)\n", msg_info.msg_lspid, msg_info.msg_lrpid);
printf("最后发送(接收)消息的时间:%s(%s)\n", ctime(&(msg_info.msg_stime)), ctime(&(msg_info.msg_rtime)));
printf("最后变化的时间:%s\n", ctime(&(msg_info.msg_ctime)));
printf("消息UID=%d, GID=%d\n", msg_info.msg_perm.uid, msg_info.msg_perm.gid);
}
int main(){
int ret = -1;
int msg_flags, msg_id;
key_t key;
struct msgmbuf{
int mtype;
char mtext[10];
};
struct msgmbuf msg_mbuf;
struct msqid_ds msg_info;
int msg_sflags, msg_rflags;
char *msgpath = "/ipc/msg";
//键值构建函数,获取IPC键值。
key = ftok(msgpath, 'c');
if(key == -1){
printf("ftok failed: %d!\n", errno);
return -1;
}
printf("ftok succeed: %d!\n", key);
//msgget()用来创建或者获取消息队列,
msg_flags = 0;
msg_flags |= IPC_CREAT;
msg_flags |= IPC_EXCL;
msg_id = msgget(key, msg_flags|0x0666);
printf("msg flag is %d\nmsgget return: %d\n", msg_flags, msg_id);
if(msg_id == -1){
printf("msgget failed: %s!\n", strerror(errno));
return -1;
}
printf("msgget succeed: %d!\n", msg_id);
msg_show_attr(msg_id, msg_info);
//开始发送消息
//并且此处设置为了IPC_NOWAIT,因此不会等待消息发送成功!即为异步执行!
msg_sflags = IPC_NOWAIT;
msg_mbuf.mtype = 10;
memcpy(msg_mbuf.mtext, "测试消息", sizeof("测试消息"));
ret = msgsnd(msg_id, &msg_mbuf, sizeof("测试消息"), msg_sflags);
if(ret == -1){
printf("msgsnd failed!\n");
}else{
printf("msgsnd succeed!\n");
}
msg_show_attr(msg_id, msg_info);
//开始接收消息
struct msgmbuf msgmbuf_r;
msg_rflags = IPC_NOWAIT|MSG_NOERROR;
ret = msgrcv(msg_id, &msgmbuf_r, 10, 10, msg_rflags);//成功返回接收的数据长度
if(ret == -1){
printf("msgrcv failed: %d!\n", errno);
}else{
printf("msgrcv succeed, msg length: %d.\n", ret);
}
msg_show_attr(msg_id, msg_info);
return 0;
}