linux进程间通信-------消息队列
2017-06-21 22:50
197 查看
消息队列属于IPC
两个进程间要通过消息队列进行通信,比如A通过消息队列给B传送一个消息。首先A要建立一个消息队列,然后A往该消息队列里面发送消息(由一个有特殊形式的结构体构成,包括数据类型和数据内容),当不需要使用这个消息队列的时候删除消息队列。B要做的事情是打开消息队列,打开方式是用和A里面一样的键值打开对应的消息队列,然后接收消息队列的消息(即结构体中某个类型的数据),结束。
相关函数
创建/打开消息队列
msgget
发送数据
msgsnd
从消息队列取消息
msgrcv
删除消息队列
msgctl
例如A进程代码
#include
#include
#include
#include
#include
#include
struct msgt
{
long
msgtype;
char
msgtext[1024];
};
void main()
{
int
msqid;
int
msg_type;
char
str[256];
struct
msgt msgs;
//创建消息队列
msqid =
msgget(1025, IPC_CREAT);
//循环
while(1)
{
printf("please input message type, 0 for quit!\n");
//获取消息类型
scanf("%d", &msg_type);
//如果用户输入的消息为0,则退出
if(msg_type == 0)
break;
printf("please input message data!\n");
//获取消息数据
scanf("%s", str);
msgs.msgtype = msg_type;
strcpy(msgs.msgtext, str);
//发送消息
msgsnd(msqid, &msgs, sizeof(struct msgt), 0);
}
//删除消息队列
msgctl(msqid, IPC_RMID, 0);
}
B进程代码
#include
#include
#include
#include
#include
#include
int msqid;
struct msgt
{
long
msgtype;
char
msgtext[1024];
};
void myprocess()
{
struct
msgt ms;
int
x;
x =
msgrcv(msqid, &ms, sizeof(struct msgt), 0, 0);
printf("the receive text: %s
%d\n", ms.msgtext, x);
}
void main()
{
int
i;
int
cpid;
//打开消息队列
msqid =
msgget(1025, IPC_EXCL);
printf("the msqid is %d\n", msqid);
myprocess();
}
两个进程间要通过消息队列进行通信,比如A通过消息队列给B传送一个消息。首先A要建立一个消息队列,然后A往该消息队列里面发送消息(由一个有特殊形式的结构体构成,包括数据类型和数据内容),当不需要使用这个消息队列的时候删除消息队列。B要做的事情是打开消息队列,打开方式是用和A里面一样的键值打开对应的消息队列,然后接收消息队列的消息(即结构体中某个类型的数据),结束。
相关函数
创建/打开消息队列
msgget
发送数据
msgsnd
从消息队列取消息
msgrcv
删除消息队列
msgctl
例如A进程代码
#include
#include
#include
#include
#include
#include
struct msgt
{
long
msgtype;
char
msgtext[1024];
};
void main()
{
int
msqid;
int
msg_type;
char
str[256];
struct
msgt msgs;
//创建消息队列
msqid =
msgget(1025, IPC_CREAT);
//循环
while(1)
{
printf("please input message type, 0 for quit!\n");
//获取消息类型
scanf("%d", &msg_type);
//如果用户输入的消息为0,则退出
if(msg_type == 0)
break;
printf("please input message data!\n");
//获取消息数据
scanf("%s", str);
msgs.msgtype = msg_type;
strcpy(msgs.msgtext, str);
//发送消息
msgsnd(msqid, &msgs, sizeof(struct msgt), 0);
}
//删除消息队列
msgctl(msqid, IPC_RMID, 0);
}
B进程代码
#include
#include
#include
#include
#include
#include
int msqid;
struct msgt
{
long
msgtype;
char
msgtext[1024];
};
void myprocess()
{
struct
msgt ms;
int
x;
x =
msgrcv(msqid, &ms, sizeof(struct msgt), 0, 0);
printf("the receive text: %s
%d\n", ms.msgtext, x);
}
void main()
{
int
i;
int
cpid;
//打开消息队列
msqid =
msgget(1025, IPC_EXCL);
printf("the msqid is %d\n", msqid);
myprocess();
}
相关文章推荐
- linux C-(进程间通信 消息队列)
- [转]Linux环境进程间通信 -- 消息队列
- Linux进程间通信之消息队列
- Linux进程间通信——消息队列
- Linux进程间通信(二)——共享内存、消息队列
- Linux环境进程间通信系列(三):消息队列
- Linux进程间通信: 消息队列
- linux进程间通信(system v消息队列,阻塞式)实例
- Linux环境进程间通信(三):消息队列
- LINUX学习笔记15——进程间通信4消息队列
- Linux进程间通信: 消息队列
- Linux环境进程间通信(三):消息队列
- Linux环境进程间通信(三):消息队列
- linux进程间通信(posix消息队列)实例
- Linux环境进程间通信(三):消息队列
- linux进程间通信之消息队列
- Linux环境进程间通信(三)消息队列
- Linux高级进程间通信:消息队列
- Linux进程间通信——消息队列
- Linux环境进程间通信(三):消息队列