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

常用的进程间通信方法,消息队列,共享内存,信号量数组

直接看程序

#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 16
struct 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 16
struct 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绝对值的消息





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值