版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengqiuming/article/details/89046535
一 接收程序代码
1 代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
struct my_msg_st
{
long int my_msg_type;
char some_text[BUFSIZ];
};
int main()
{
int running = 1;
int msgid;
struct my_msg_st some_data;
long int msg_to_receive = 0; //如果为0,表示消息队列中的所有消息都会被读取
//创建消息队列:
msgid = msgget((key_t)1234,0666|IPC_CREAT);
if(msgid == -1)
{
fprintf(stderr,"msgget failed with error: %d\n", errno);
exit(EXIT_FAILURE);
}
//接收消息队列中的消息直到遇到一个end消息。最后,消息队列被删除。
while(running)
{
//第5个参数为0表示阻塞方式,当消息队列为空,一直等待
if(msgrcv(msgid, (void *)&some_data, BUFSIZ, msg_to_receive, 0) == -1)
{
fprintf(stderr, "msgrcv failed with errno: %d\n", errno);
exit(EXIT_FAILURE);
}
printf("You wrote: %s", some_data.some_text);
if(strncmp(some_data.some_text, "end", 3)==0)
{
running = 0;
}
}
if(msgctl(msgid, IPC_RMID, 0)==-1) // 删除消息队列
{
fprintf(stderr, "msgctl(IPC_RMID) failed\n");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
2 说明
接收者使用msgget来获得消息队列标识符,并且等待接收消息,直到接收到特殊消息end。然后它会使用msgctl删除消息队列进行一些清理工作。
二 消息发送程序
1 代码
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define MAX_TEXT 512
struct my_msg_st
{
long int my_msg_type;
char some_text[MAX_TEXT];
};
int main()
{
int running = 1;
struct my_msg_st some_data;
int msgid;
char buffer[BUFSIZ];
msgid = msgget((key_t)1234, 0666|IPC_CREAT); //用一个整数作为一个键值
if(msgid==-1)
{
fprintf(stderr,"msgget failed with errno: %d\n", errno);
exit(EXIT_FAILURE);
}
while(running)
{
printf("Enter some text: ");
fgets(buffer, BUFSIZ, stdin);
some_data.my_msg_type = 1;
strcpy(some_data.some_text, buffer);
if(msgsnd(msgid, (void *)&some_data, MAX_TEXT, 0)==-1)
{
fprintf(stderr, "msgsnd failed\n");
exit(EXIT_FAILURE);
}
if(strncmp(buffer, "end", 3) == 0)
{
running = 0;
}
}
exit(EXIT_SUCCESS);
}
2 说明
发送者程序使用msgget创建一个消息队列,然后使用msgsnd函数向队列中添加消息。
三 运行
1 在第1个终端启动接收者程序
[root@localhost test]# g++ test.cpp -o test
[root@localhost test]# ./test
2 在第2个终端启动发送者程序,并开始发送数据
[root@localhost test]# g++ send.cpp -o send
[root@localhost test]# ./send
Enter some text: how are you!
Enter some text: end
3 第1个终端输出发送的结果
You wrote: how are you!
You wrote: end