linux扩充消息队列,Linux关于消息队列的使用分享

今天完成消息队列的使用。

消息队列类似FIFO,但是可以实现随机查询。

主要函数:msgget,msgsnd,msgrcv,msgctl

实验实现两个进程之间的通信。

一个发送,一个接受。并不需要额外实现进程同步。

源代码来自华清远见:

发送:

#include

#include

#include

#include

#include

#include

#include

#define BUFFER_SIZE 512

struct message

{

long msg_type;

char msg_text[BUFFER_SIZE];

};

int main()

{

int qid;

key_t key;

struct message msg;

//ftok根据不同路径和关键字产生标准的KEY

if((key = ftok(“.”, ‘a’)) == -1)

{

perror(“ftok”);

exit(1);

}

if((qid = msgget(key, IPC_CREAT|0666)) == -1)//创建

{

perror(“msgget”);

exit(1);

}

printf(“open queue %dn”, qid);

while(1)

{

printf(“enter some message to the queue:”);

if((fgets(msg.msg_text, BUFFER_SIZE, stdin)) == NULL)

{

puts(“no message”);

exit(1);

}

msg.msg_type = getpid();//消息类型为进程号

if((msgsnd(qid, &msg, strlen(msg.msg_text), 0)) < 0)//发送消息

{

perror(“message posted”);

exit(1);

}

if(strncmp(msg.msg_text, “quit”, 4) == 0)

{

break;

}

}

exit(0);

}

接收:

#include

#include

#include

#include

#include

#include

#include

#define BUFFER_SIZE 512

struct message

{

long msg_type;

char msg_text[BUFFER_SIZE];

};

int main()

{

int qid;

key_t key;

struct message msg;

if((key = ftok(“.”, ‘a’)) == -1)

{

perror(“ftok”);

exit(1);

}

if((qid = msgget(key, IPC_CREAT|0666)) == -1)//创建

{

perror(“msgget”);

exit(1);

}

printf(“open queue %dn”, qid);

do

{

memset(msg.msg_text, 0, BUFFER_SIZE);

if(msgrcv(qid, (void*)&msg, BUFFER_SIZE, 0, 0) < 0)//接收消息

{

perror(“msgrcv”);

exit(1);

}

printf(“the message from process %d : %s”, msg.msg_type, msg.msg_text);

}while(strncmp(msg.msg_text, “quit”, 4));

if((msgctl(qid, IPC_RMID, NULL)) < 0)//从

{

perror(“msgctl”);

exit(1);

}

exit(0);

}

打开两个终端,1号发送,2号接收

—-想了解更多的linux相关异常处理怎么解决关注

本文来自网络收集,不代表猴子技术宅立场,如涉及侵权请点击右边联系管理员删除。

如若转载,请注明出处:https://www.ssfiction.com/linuxxt/61445.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值