消息队列:
1、 IPC的一种,按照消息的类型来发送和接收信息
2、注意要设计消息结构体
运行效果:
写端:
读端:
write.c
#include<stdio.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#define MSG_LEN (sizeof(MSG)-sizeof(long))
typedef struct _msg_
{
long type;
char buf[1024];
}MSG;
MSG msg ;
int main(int argc, const char *argv[])
{
key_t key;
msg.type = 100;
int msg_id;
if((key = ftok(argv[1],'k')) < 0)
{
perror("fail to ftok:");
exit(EXIT_FAILURE);
}
if((msg_id = msgget(key,IPC_CREAT | 0666)) < 0)
{
perror("fail to msgget");
exit(EXIT_FAILURE);
}
printf("msg_id write : %d\n",msg_id);
while(1)
{
fgets(msg.buf,sizeof(msg.buf),stdin);
msg.buf[strlen(msg.buf) - 1] = '\0';
printf("msg.buf : %s\n", msg.buf);
if(msgsnd(msg_id,&msg,MSG_LEN,0) < 0)
{
perror("fail to msgsnd");
exit(EXIT_FAILURE);
}
if(strncmp(msg.buf,"quit",4) == 0)
{
break;
}
}
return 0;
}
read.c
#include<stdio.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#define MSG_LEN (sizeof(MSG)-sizeof(long))
typedef struct _msg_
{
long type;
char buf[1024];
}MSG;
MSG msg ;
int main(int argc, const char *argv[])
{
key_t key;
int msg_id;
if((key = ftok(argv[1],'k')) < 0)
{
perror("fail to ftok:");
exit(EXIT_FAILURE);
}
if((msg_id = msgget(key,IPC_CREAT | 0666)) < 0)
{
perror("fail to msgget");
exit(EXIT_FAILURE);
}
printf("msg_id read : %d\n",msg_id);
while(1)
{
if(msgrcv(msg_id,&msg,MSG_LEN,100,0) < 0)
{
perror("fail to msgrcv");
exit(EXIT_FAILURE);
}
printf("MSG TYPE:%ld\n",msg.type);
printf("MSG : %s\n",msg.buf);
if(strncmp(msg.buf,"quit",4) == 0)
{
break;
}
}
return 0;
}