linux消息队列简析
消息队列提供了一种在两个不相关的进程之间传递数据的相当简单且有效的方法:
消息发送端代码:
#include <stdio.h>
#include <stdlib.h>fgets(buffer, BUFSIZ, stdin);
//发送类型为8的消息
message.message_type = 8;}
消息接收端代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/msg.h>
#include <sys/ipc.h>
#include <sys/types.h>
int message_id;
struct my_message
{
long int message_type;
char buf[BUFSIZ];
};
struct my_message message;
int main(void)
{
int ret;
int running = 1;
//接收类型为8的消息
long int recv_type = 8;
message_id = msgget((key_t)1234, 0666|IPC_CREAT);
if(message_id == -1)
{
perror("fail to msgget");
exit(1);
}
memset(&message, 0, sizeof(struct my_message));
while(running)
{
ret = msgrcv(message_id, &message, BUFSIZ, recv_type,0);
if(ret > 0)
{
printf("received message %s", message.buf);
}
else
{
perror("fail to msgrcv");
}
if(strncmp(message.buf, "end", 3) == 0)
{
printf("1\n");
running = 0;
}
}
return 0;
}