所谓消息队列就是指一个消息链表。int msgget(key_t, int flag):创建和打开队列int msgsnd(int msqid, struct msgbuf *msgp, size_t msgsz, int flag):发送消息,msgid是消息队列的id,msgp是消息内容所在的缓冲区,msgsz是消息的大小,msgflg是标志。int msgrcv(int msqid, struct msgbuf *msgp, size_t msgsz, long msgtyp, int flag):接受消息,msgtyp是期望接收的消息类型。int msgctl(int msqid, int cmd, struct msqid_ds *buf):控制
- #include <sys/types.h>
- #include <sys/ipc.h>
- #include <sys/msg.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <string.h>
- #define BUFSZ 512
- struct message{ //消息结构体
- long msg_type;
- char msg_text[BUFSZ];
- };
-
- int main()
- {
- int qid;
- key_t key;
- int len;
- struct message msg;
-
- if((key=ftok(".","a"))==-1) //ftok获得一个key
- {
- perror("ftok");
- exit(1);
- }
- if((qid=msgget(key,IPC_CREAT|0666))==-1){ //创建一个消息队列
- perror("msgget");
- exit(1);
- }
- printf("opened queue %d
",qid);
- puts("Please enter the message to queue:");
- if((fgets(msg.msg_text,BUFSZ,stdin))==NULL) // 从标准输入获取输入
- {
- puts("no message");
- exit(1);
- }
- msg.msg_type = getpid();
- len = strlen(msg.msg_text);
- if((msgsnd(qid,&msg,len,0))<0){ //发送消息
- perror("message posted");
- exit(1);
- }
- if(msgrcv(qid,&msg,BUFSZ,0,0)<0){ //接收消息
- perror("msgrcv");
- exit(1);
- }
- printf("message is:%s
",(&msg)->msg_text);
- if((msgctl(qid,IPC_RMID,NULL))<0){ //删除消息
- perror("msgctl");
- exit(1);
- }
- exit(0);
- }
RedHat AS4下的openoffice 启动后无响应的解决办法Linux下打造中文man帮助相关资讯 Linux知识
- 时光总是太匆匆!Linux已经诞生23 (08/29/2014 14:12:03)
- Linux虚拟文件系统之文件打开(sys (02/14/2012 11:41:54)
- 2012 年 Linux 峰会时间表 (02/14/2012 06:47:27)
| - 报告称当前 Linux 人才抢手 高薪也 (02/15/2012 06:35:56)
- 解析企业为何选择Linux及其特别之 (02/14/2012 08:17:59)
- Linux禁用字符闪烁的方法 (11/02/2011 10:28:25)
|
本文评论 查看全部评论 (0)