Linux进程间通信——使用消息队列
Linux下进程通讯消息队列
//接收端
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
struct msgbuf
{
long mtype;//消息类型,必须>0
int cnt;
char buff[100];
};
int main(int argc,char *argv[])
{
if(argc!=2)
{
printf("格式:./app <消息类型>\n");
return 0;
}
// key_t key=ftok("msgsnd.c", 1234);//生成键值
// if(key==-1)
// {
// printf("生成键值失败err=%s\n",strerror(errno));
// return 0;
// }
// printf("key=%#x\n",key);
//收发端要约定好一个同样的键值
int msqid=msgget((key_t)123456,IPC_CREAT|0666);//创建消息队列
if(msqid==-1)
{
printf("创建消息队列失败err=%s\n",strerror(errno));
return 0;
}
printf("msqid=%d\n",msqid);
struct msgbuf msg;
int msg_size=sizeof(msg)-sizeof(long);//消息大小
long msgtyp=atoi(argv[1]);//要写读取的消息类型
//从消息队列中取数据
ssize_t size=msgrcv(msqid,&msg,msg_size,msgtyp,0);
if(size==-1)
{
printf("读取消息失败err=%s\n",strerror(errno));
}
else
{
printf("------------读取消息成功size:%ld----------------\n",size);
printf("\tmtype=%ld\n",msg.mtype);
printf("\tcnt=%d\n",msg.cnt);
printf("\tbuff=%s\n",msg.buff);
}
return 0;
}
//发送端
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
struct msgbuf
{
long mtype;//消息类型,必须>0
int cnt;
char buff[100];
};
int main(int argc,char *argv[])
{
if(argc!=4)
{
printf("格式:./app <消息类型> <消息数据> <消息内容>\n");
return 0;
}
// key_t key=ftok("msgsnd.c", 1234);//生成键值
// if(key==-1)
// {
// printf("生成键值失败err=%s\n",strerror(errno));
// return 0;
// }
// printf("key=%#x\n",key);
int msqid=msgget((key_t)123456,IPC_CREAT|0666);//创建消息队列
if(msqid==-1)
{
printf("创建消息队列失败err=%s\n",strerror(errno));
return 0;
}
printf("msqid=%d\n",msqid);
struct msgbuf msg;
msg.mtype=atoi(argv[1]);//消息类型
msg.cnt=atoi(argv[2]);//消息数据
strcpy(msg.buff,argv[3]);//消息内容
int msg_size=sizeof(msg)-sizeof(long);//消息大小,总大小-消息类型大小
/*添加消息到队列*/
int size=msgsnd(msqid,&msg,msg_size,0);
if(size==-1)
{
printf("写入消息失败err=%s\n",strerror(errno));
}
else printf("消息写入成功\n");
return 0;
}