IO进线程:消息队列

消息队列可以使用类型来发送和接收消息

key: IPC_PRIVATE, ftok

创建或打开消息队列:msgget

添加消息(发送消息): msgsnd

读取消息(接收消息): msgrcv

控制消息(删除消息队列): msgctl

------------------------------------------------------------------------------

信息队列的创建与添加信息:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

struct msgbuf{
    long mtype;   //消息类型
    char mtext[100]; //消息正文
};

int main(int argc, char *argv[])

    key_t key = ftok(".", 'b');
    if (key < 0)
    {
        perror("ftok");
        return -1;
    }

    int msgid = msgget(key, IPC_CREAT|0777);
    if (msgid < 0)
    {
        perror("msgget");
        return -1;
    }

    //添加消息
    struct msgbuf buf = {1};
    while (1)
    {
        printf("Input type: ");
        scanf("%ld", &buf.mtype);
        getchar();
        printf("Send: ");
        fgets(buf.mtext, sizeof(buf.mtext), stdin);
        if (0 > msgsnd(msgid, &buf, sizeof(buf)-sizeof(long), 0))
        {
            perror("msgsnd");
            break;
        }
        if (strncmp(buf.mtext, "quit", 4) == 0)
            break;
    }

    return 0;


---------------------------------------------------------------------------

信息队列的读取与删除信息队列:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

struct msgbuf{
    long mtype;   //消息类型
    char mtext[100]; //消息正文
};

int main(int argc, char *argv[])

    key_t key = ftok(".", 'b');
    if (key < 0)
    {
        perror("ftok");
        return -1;
    }

    int msgid = msgget(key, 0777);
    if (msgid < 0)
    {
        perror("msgget");
        return -1;
    }

    //读取消息
    struct msgbuf buf;
    while (1)
    {
        if (0 > msgrcv(msgid, &buf, sizeof(buf)-sizeof(long), 1, 0))
        {
            perror("msgrcv");
            break;
        }
        printf("recv: %s\n", buf.mtext);
        if (strncmp(buf.mtext, "quit", 4) == 0)
            break;
    }
    sleep(1);
    if (0 > msgctl(msgid, IPC_RMID, NULL))
    {
        perror("msgctl");
        return -1;
    }

    return 0;

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

এ᭄星辰

混口饭吃。。。。。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值