Linux下的消息队列的使用

本文通过两个示例程序介绍了消息队列的使用方法,包括如何创建消息队列、发送及接收消息。消息队列能够实现进程间的一对多通信模式,在多进程中传递信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

消息队列是一种可以一对多的传输信号的方式


#include<stdio.h>

#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<string.h>
#include<stdlib.h>
struct msgbuf
{
long mtype;
char mtext[1024];
};
int main()
{
char buffer[1024] = {0};
key_t key = ftok(".", 2);                                            //将文件名转化为键值
if (-1 == key)                       
{
perror("key");
}
int msgid = msgget(key, IPC_CREAT);                       //创建消息队列
if (msgid == -1)
{
perror("msgget");
}
while(1)
{
struct msgbuf buf;
scanf("%d %s", &buf.mtype, buf.mtext);

msgsnd(msgid, &buf, sizeof(buf.mtext), 0);                //发送信息给消息队列
memset(buf.mtext, 0, 1024);                                   
}
return 0;

}


-----------------------------------------分割线--------------------------------------------------

#include<stdio.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<string.h>
#include<stdlib.h>
struct msgbuf
{
long mtype;
char mtext[1024];
};
int main()
{
key_t key = ftok(".", 2);                                            
if (-1 == key)
{
perror("key");
}
int msgid = msgget(key, IPC_CREAT);
if (msgid == -1)
{
perror("msgget");
}
int type;
scanf("%d", &type);


while(1)
{
struct msgbuf buf;
msgrcv(msgid, &buf, sizeof(buf.mtext), type, 0);               //接受信号,其中type为接受的信号编码
printf("rcv = %s\n", buf.mtext);
}
return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值