【进程通信】消息队列简单例子
来源:互联网 发布:linux网络相关命令 编辑:程序博客网 时间:2024/05/16 18:44
常用的进程间通信方法,消息队列,共享内存,信号量数组
直接看程序
#include <stdio.h>#include <sys/types.h>#include <sys/ipc.h>#include <sys/msg.h>int main(void){ int msgid; msgid = msgget(100, IPC_CREAT | 0640); printf("msgid = %d\n", msgid); return 0;}这里msgget函数直接产生了一个消息队列,返回一个消息队列号。
int msgget(key_t key, int msgflg);
key_t是一个标志,可以由ftok生成,可参考ftok函数。也可以自己指定。
msgflg包含了一些权限,是否创建等信息。
运行完上面程序后,用ipcs查看,在下面应该多了一则消息队列的信息,包括消息数,大小等。
下面是一个传送结构体信息的例子
#include <stdio.h>#include <sys/types.h>#include <sys/ipc.h>#include <sys/msg.h>#define SIZE 16struct student_t { unsigned long type; char name[SIZE]; int chinese; int math;};/*struct msgbuf_t { unsigned long type; struct student_t data;};*/int main(void){ int msgid, ret; char buffer[SIZE]; struct student_t stu; msgid = msgget(100, 0);//前提是你已经建了一个消息队列! printf("优先级: "); fgets(buffer, SIZE, stdin); stu.type = atoi(buffer); printf("姓名: "); fgets(buffer, SIZE, stdin); sscanf(buffer, "%s", stu.name); printf("语文: "); fgets(buffer, SIZE, stdin); stu.chinese = atoi(buffer); printf("数学: "); fgets(buffer, SIZE, stdin); stu.math = atoi(buffer); ret = msgsnd(msgid, &stu, sizeof(stu) - sizeof(unsigned long), 0); printf("ret = %d\n", ret); return 0;}
msgsnd是将stu中的内容发到消息队列中!
下面是一个接收的例子#include <stdio.h>#include <sys/types.h>#include <sys/ipc.h>#include <sys/msg.h>#define SIZE 16struct student_t { unsigned long type; char name[SIZE]; int chinese; int math;};int main(void){ int msgid, type, ret; char buffer[SIZE]; struct student_t stu; msgid = msgget(100, 0); printf("要接收的消息类型: "); scanf("%d", &type); ret = msgrcv(msgid, &stu, sizeof(stu) - sizeof(unsigned long), type, 0); if (ret > 0) { printf("type = %d, name = %s, chinese = %d, math = %d\n", stu.type, stu.name, stu.chinese, stu.math); } return 0;}
用函数msgrcv来接收其中的内容,
每运行一次,发现消息队列数减少一个,如果没有消息在队列里面,会阻塞的等待。
参数type使我们可以指定想要哪一种消息,
type == 0 返回消息队列中第一个消息
type > 0返回队列中消息类型为type的第一个消息
type < 0返回队列中消息类型值小于或等于type绝对值的消息
- 【进程通信】消息队列简单例子
- 进程通信消息队列
- [进程通信] 消息队列
- 进程通信--消息队列
- 进程通信-----消息队列
- 进程通信--消息队列
- Linux进程间通信(简单的消息队列通信)
- Linux 进程间通信(posix消息队列 简单)实例
- 简单的,父子进程间通过消息队列通信。
- 简单的,不同进程间通过消息队列通信
- 进程通信之消息队列
- 进程通信之消息队列
- linux消息队列进程通信
- 进程间消息队列通信
- linux消息队列进程通信
- 进程间通信:消息队列
- linux消息队列进程通信
- 进程间通信--消息队列
- linux下多定时器源码
- ORACLE----触发器,存储过程及JOB
- Page is already covered by another Data Binder. Cannot be covered by this Data Binder again
- (转)使用GradientFill实现控件颜色渐变
- 网页中插入视频播放代码全集
- 【进程通信】消息队列简单例子
- MySQL、SQL Server 、 Oracle、Access的sql语句区别
- 【总结】java命令解析以及编译器,虚拟机如何定位类
- WLAN学习 ap ac dns ssl nal radius http dhcp aaa chap...
- jni和C++通信中文乱码的问题
- MFC集合
- 【视听震撼】娱乐红人马宁的出现代表着新一轮的男色风潮来袭
- datetime类型数据
- Android开发--如何优化你的UI