您的位置:首页 > 编程语言

进程间通信使用消息队列的试验代码与总结

2017-06-07 23:19 495 查看
1、先说结论,消息队列用于进程间消息传递使用很方便,特别适用于异步通信。

2、试验思路:验证生产者和消费者之间的异步通信,同时通过linux上的命令行观察消息队列的使用情况。

3、试验结果:

a. 生产者(发送方)轮询从命令行上接收字符串,消费者(接收方)进程会自动打印内容。

             

     b. 生产者先发送很多信息,消费者还没有启动。后来,消费者进程才启动,消费者进程也是可以正常显示数据的。

    c. 在生产者和消费者配合的过程中,通过ipcs命令行查看消息队列的状态。

  d. 生产者先生产,然后再启动消费者。此时从命令行上查看ipcs,可以看到有缓存的消息

后启动消费者进程。可见缓存的消息已被处理结束。

 下面是接收方和发送方的源代码:

接收方 rcv.c 

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.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;

msgid = msgget((key_t) 1234, 0666 | IPC_CREAT);

if( -1 == msgid)
{
fprintf(stderr, "msgget failed with error: %d \n", errno);
exit(EXIT_FAILURE);
}

while(running)
{
if( msgrcv(msgid, (void *)&some_data, BUFSIZ, msg_to_receive, 0) == -1)
{
fprintf(stderr, "msgrcv failed with error : %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");
exit(EXIT_FAILURE);
}

exit(EXIT_SUCCESS);
}



发送方 snd.c
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>

#include <sys/msg.h>

#define MAX_TEXT 512

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;
char buffer[BUFSIZ];

msgid = msgget((key_t) 1234, 0666 | IPC_CREAT);

if( -1 == msgid)
{
fprintf(stderr, "msgget failed with error: %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 with error : %d \n", errno);
exit(EXIT_FAILURE);
}

if(strncmp(buffer, "end", 3) == 0)
{
running = 0;
}
}

exit(EXIT_SUCCESS);
}


编译方法:
[zhou@localhost msgqueue]$ gcc rcv.c -o rcv.o

[zhou@localhost msgqueue]$ gcc snd.c -o snd.o

[zhou@localhost msgqueue]$ chmod 777 rcv.o

[zhou@localhost msgqueue]$ chmod 777 snd.o

[zhou@localhost msgqueue]$
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息