【Linux技术】linux之消息队列
来源:互联网 发布:算法设计与分析怎么学 编辑:程序博客网 时间:2024/06/05 08:30
1.机制
2.源码
消息队列的运行方式与命名管道非常相似。
欲与其他进程通信的进程只需要将消息发送到消息队列中,目的进程就从消息队列中读取需要的消息。2.源码
1)发送方
//msg_send.c#include <sys/types.h>#include <sys/msg.h>#include <unistd.h>#include <stdlib.h>#include <stdio.h>int main(){ int msg_id,msg_flags; int reval; char send_msg[64]; msg_flags=IPC_CREAT|0666; msg_id=msgget((key_t)456,msg_flags); if(-1==msg_id) { printf("msg create error.\n"); exit(EXIT_FAILURE); } memset(send_msg,0,64); sprintf(send_msg,"Hi,I'm %d.",getpid()); reval=msgsnd(msg_id,send_msg,sizeof(send_msg),0); if(-1==reval) { printf("message send error.\n"); exit(EXIT_FAILURE); } else printf("Send message:%s\n",send_msg); return 0;}
2)接收方
//msg_rcvr.c#include <sys/types.h>#include <sys/msg.h>#include <unistd.h>#include <stdlib.h>#include <stdio.h>int main(){ int msg_id,msg_flags; int reval; char send_msg[64]; msg_flags=IPC_CREAT|0666; msg_id=msgget((key_t)456,msg_flags); if(-1==msg_id) { printf("msg create error.\n"); exit(EXIT_FAILURE); } memset(send_msg,0,64); reval=msgrcv(msg_id,send_msg,64,0,0); if(-1==reval) { printf("message send error.\n"); exit(EXIT_FAILURE); } else printf("Received msg:%s\n",send_msg); reval=msgctl(msg_id,IPC_RMID,0); if(-1==reval) { printf("remove msg queue error\n"); exit(EXIT_FAILURE); } return 0;}
3.mystery注解
1)msgget()函数与信号量的semget()函数相似,作用是创建一个消息队列。
2)msqid为消息队列ID
3)消息队列可以在几个进程之间复用,具有一定的独立性,比命名管道更加灵活,也不需要打开与关闭。
4)在最后一个进程使用完消息队列后,不要忘记删除这个消息队列
本文出自 “成鹏致远” 博客,请务必保留此出处http://infohacker.blog.51cto.com/6751239/1155035
- 【Linux技术】linux之消息队列
- linux之消息队列
- Linux通信之消息队列
- Linux IPC 之消息队列
- linux IPC之消息队列
- linux IPC之消息队列
- Linux IPC 之消息队列
- linux笔记之消息队列
- linux进程间通信之消息队列
- Linux进程间通讯之消息队列
- linux进程间通信之消息队列
- linux进程间通信之消息队列
- Linux进程间通信之消息队列
- Linux消息队列之命令行相关
- Linux消息队列之命令行相关
- Linux进程间通讯之消息队列
- Linux进程通信之消息队列
- linux 进程间通信之消息队列
- iOS用ASIFormDataRequest实现图片上传
- 自动化测试的优缺点
- Maven release for Git
- 【Linux技术】Fedora下 Mysql 安装及配置
- 【Linux技术】linux连接mysql错误解决方案
- 【Linux技术】linux之消息队列
- 【Linux技术】linux之thread错误解决方案
- 深入浅出UML类图
- 【Linux技术】linux之多线程同步互斥技术
- 【Linux技术】linux套接字技术之tcp
- linux 内核GPIO 模拟 I2C
- 【Linux技术】linux无连接编程技术
- 全面掌握Java的异常处理机制
- 【Linux技术】linux网络多路复用IO技术