消息队列.ppt.pptVIP

  • 149
  • 0
  • 约1.79千字
  • 约 15页
  • 2016-04-23 发布于天津
  • 举报
消息队列.ppt

单击此处编辑母版标题样式 Linux进程间通信 消息队列 * 主要内容 传统进程通信 信号通信 管道通信 System V IPC进程通信 消息队列 共享主存 信号量 Socket网络进程通信 * 消息队列 消息是一个格式化的可变长信息单位 消息队列就是一些消息的列表。用户可以从消息队列中添加消息和读取消息等。 消息机制允许一个进程向其他进程发送一个消息 IPC消息队列资源的限制 IPC消息队列的缺省数为16 每个消息的缺省大小8192字节 队列中全部信息的缺省大小为16384字节 消息使用以下两种数据结构 消息首部:struct msg_msg 消息队列头表:msg_queue 消息队列 * 消息队列各数据结构之间的关系 消息队列 消息队列 消息队列使用步骤 第1步,消息队列的实现包括创建或打开消息队列,使用的函数是msgget(),创建的消息队列的数量会受到系统消息队列数量的限制 第2步添加消息、读取消息。添加消息使用的函数是msgsnd()函数,它把消息添加到已打开的消息队列末尾;读取消息使用的函数是msgrcv(),它把消息从消息队列中取走,与FIFO不同的是,这里可以指定取走某一条消息; 还可以控制消息队列,使用的函数是msgctl(),它可以完成多项功能,其中可以用它删去消息队列。 消息创建或打开 消息发送 内核须对msgsnd( )函数完成的工作 检查消息队列描述符、许可权及消息长度 若合法,继续执行 否则,返回 内核为消息分配数据区,将消息正文拷贝到消息数据区 分配消息首部,并将它链入消息队列的末尾 修改消息队列头表,如队列中的消息数、字节总数等 唤醒等待消息的进程 消息首部:struct msg_msg 消息队列头表:msg_queue 消息读取 消息控制(删除消息) 举例 #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) {perror(ftok); exit(1);} if ((qid = msgget(key,IPC_CREAT|0666)) == -1) { perror(msgget);exit(1);} 构造消息结构 printf(Opened queue %d\n,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, getpid(), 0) 0) { perror(msgrcv); exit(1);} printf(message is:%s\n,(msg)-msg_text); /*从系统内核中移走消息队列 */ if ((msgctl(qid, IPC_RMID, NULL)) 0) { perror(msgctl); exit(1); } exit(0); } 单击此处编辑母版标题样式

文档评论(0)

1亿VIP精品文档

相关文档