linux 消息对lie_Linux_Linux关于消息队列的使用,今天完成消息队列的使用。 - phpStudy...

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 %d\n", 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 %d\n", 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系统下http服务不能解释php的问题

对联广告

ASP:一个网站空间多个域名访问

asp.net 下载文件时根据MIME类型自动判断保存文件的扩展名

ADO.NET Entity Framework(5)esql (一)

平均分配,移动欠费催收款数据的分配应用实例

javascript实现动态增加删除表格行(兼容IE/FF)

修改asp.net2.0内置成员管理中的强密码规则

如何获取SQL Server数据库里表的占用容量大小

巧用Windows Server 2008的NPS策略

用ASP开"多线程"

Windows 2008启用网络身份验证功能

JS应用在Firebug中的扩展架构模式

Linux操作系统下Shell语句元字符知识笔记

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值