消息队列
- 消息队列是System IPC对象的一种。
- 消息队列就是一个消息的列表。用户可以在消息队列中添加消息、读取消息等。
- 多个进程通过消息队列的标识符对消息数据进行传送。
- 消息列队可以按照类型来发送/接收消息。
案例要求:
两个进程通过消息队列,轮流将键盘输入的字符串发送给对方,接收并打印对方发送的消息。
进程A
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
typedef struct
{
long mtype;
char mtext[64];
} MSG;
#define LEN (sizeof(MSG) - sizeof(long))
#define TypeA 100
#define TypeB 200
int main()
{
key_t key;
int msgid;
MSG buf;
if((key = ftok(".",'q'))== -1)
{
perror("ftok");
exit(-1);
}
if((msgid = msgget(key,IPC_CREAT|0666)) < 0)
{
perror("msgget");
exit(-1);
}
while(1)
{
buf.mtype = TypeB;
printf("input>");
fgets(buf.mtext,64,stdin);
msgsnd(msgid,&buf,LEN,0);
if(strcmp(buf.mtext,"quit\n") == 0)break;
if(msgrcv(msgid,&buf,LEN,TypeA,0) < 0)
{
perror("msgrcv");
exit(-1);
}
if(strcmp(buf.mtext,"quit\n") ==0)
{
msgctl(msgid,IPC_RMID,0);
exit(0);
}
printf("recv from clientB :%s",buf.mtext);
}
return 0;
}
~
进程B
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
typedef struct
{
long mtype;
char mtext[64];
} MSG;
#define LEN (sizeof(MSG) - sizeof(long))
#define TypeA 100
#define TypeB 200
int main()
{
key_t key;
int msgid;
MSG buf;
if((key = ftok(".",'q'))== -1)
{
perror("ftok");
exit(-1);
}
if((msgid = msgget(key,IPC_CREAT|0666)) < 0)
{
perror("msgget");
exit(-1);
}
while(1)
{
if(msgrcv(msgid,&buf,LEN,TypeB,0) < 0)
{
perror("msgrcv");
exit(-1);
}
if(strcmp(buf.mtext,"quit\n") ==0)
{
msgctl(msgid,IPC_RMID,0);
exit(0);
}
printf("recv from clientA :%s",buf.mtext);
buf.mtype = TypeA;
printf("input>");
fgets(buf.mtext,64,stdin);
msgsnd(msgid,&buf,LEN,0);
if(strcmp(buf.mtext,"quit\n") == 0)break;
}
return 0;
}
编译运行
book@100ask:~/msg$ ./clientA
input>Hello
recv from clientB :welcome
input>123
recv from clientB :456
input>over
book@100ask:~/msg$
book@100ask:~/msg$ ./clientB
recv from clientA :Hello
input>welcome
recv from clientA :123
input>456
recv from clientA :over
input>quit
book@100ask:~/msg$
程序的结构流程如下