Linux消息队列
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Linux消息队列,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2345字,纯文字阅读大概需要4分钟。
内容图文
1 #include <stdio.h> 2 #include <sys/types.h> 3 #include <sys/ipc.h> 4 #include <sys/msg.h> 5 #include <errno.h> 6 #include <string.h> 7 #include <stdlib.h> 8 9int msg_key = 1234; 1011struct MsgNode 12{ 13long nMsgType; 14char sBuf[256]; 15}; 1617int main(int argc,char** argv) 18{ 19int nMsgId = 0; 20if((argc == 2) && (strcmp(argv[1],"c") == 0)) 21 { 22 nMsgId = msgget(msg_key,IPC_EXCL); 23if(nMsgId < 0) 24 { 25 nMsgId = msgget(msg_key,0750|IPC_CREAT); 26if(nMsgId < 0) 27 { 28 perror("msgget"); 29 printf("msgget failed\n"); 30 exit(-1); 31 } 32 } 3334for(int i = 0 ;i < 10; ++i) 35 { 36 MsgNode node; 37 node.nMsgType = 1; 38 sprintf(node.sBuf,"This is the %d msg from client.\n",i); 3940if(i == 9) 41 { 42 strcpy(node.sBuf,"end\n"); 43 } 4445 printf("%s",node.sBuf); 4647int ret = msgsnd(nMsgId,&node,sizeof(node.sBuf),IPC_NOWAIT); 48if(ret < 0) 49 { 50 perror("msgsend"); 51 printf("msgsend failed"); 52 exit(-1); 53 } 54 } 55 } 56else57 { 58 nMsgId = msgget(msg_key,IPC_EXCL); 59if(nMsgId < 0) 60 { 61 printf("msgget failed\n"); 62 exit(-1); 63 } 6465bool flag = true; 66while(flag) 67 { 68 MsgNode node; 69int ret = msgrcv(nMsgId,&node,sizeof(node.sBuf),1,IPC_NOWAIT); 70if(ret == -1) 71 { 72 perror("msgrecv"); 73 printf("msgrecv failed\n"); 74 exit(-1); 75 } 76 printf("Receive Msg:%s",node.sBuf); 77//if(strncmp(node.sBuf,"end",3) == 0) 78//{ 79// flag = false; 80//};81 } 8283int ret = msgctl(nMsgId,IPC_RMID,0); 84if( ret == -1) 85 { 86 printf("msgctl failed\n"); 87 exit(-1); 88 } 89 } 9091return0; 92 }
需要注意的是
int msgsend(int msgid, constvoid *msg_ptr, size_t msg_sz, int msgflg);
及
int msgrcv(int msgid, void *msg_ptr, size_t msg_st, longint msgtype, int msgflg);
其中 size_t msg_st并不是消息结构体的大小,而是消息的大小。
如代码中定义了结构
1 struct MsgNode 2 { 3 long nMsgType; 4 char sBuf[256]; 5 };
则 size_t msg_st指的是 sizeof(MsgNode.sBuf)即不包括结构中消息类型的长度。
在接受/发送消息时如果不设置为IPC_NOWAIT则发送时如果消息队列已满则阻塞,接收时如果消息队列为空则阻塞。
原文:http://www.cnblogs.com/boyunzheyue2/p/5640423.html
内容总结
以上是互联网集市为您收集整理的Linux消息队列全部内容,希望文章能够帮你解决Linux消息队列所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。