【进程通信】消息队列简单例子

来源:互联网 发布: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绝对值的消息

	
				
		
原创粉丝点击