read date from message: msg_r.c
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<errno.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#define BUFFSIZE 2050
struct my_msg
{
long int l_msg_type;
char sz_msg_text[BUFFSIZE];
};
int main(void)
{
int n_run = 1;
int n_msgid;
struct my_msg st_msg;
long int l_rec_type;
n_msgid = msgget((key_t)1234,0666|IPC_CREAT);
if(n_msgid==-1)
{
fprintf(stderr,"create msg failed: %s!\n",strerror(errno));
exit(EXIT_FAILURE);
}
while(n_run)
{
if(msgrcv(n_msgid,(void*)&st_msg,BUFFSIZE,l_rec_type,0)==-1)
{
if(errno==EAGAIN)
{
printf("No data to read!\n");
sleep(1);
}
else
{
fprintf(stderr,"receive data error: %s !\n",strerror(errno));
exit(EXIT_FAILURE);
}
}
printf("You Write data: %s",st_msg.sz_msg_text);
if(strncmp(st_msg.sz_msg_text,"end",3)==0)
{
n_run=0;
}
}
if(msgctl(n_msgid,IPC_RMID,0)==-1)
{
fprintf(stderr,",remove msg failed:%s\n",strerror(errno));
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
write data to messag: msg_w.c
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<errno.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#define BUFFSIZE 1024
#define MAX_TEXT 2048
struct my_msg
{
long int l_msg_type;
char sz_msg_text[MAX_TEXT];
};
int main(void)
{
int n_run = 1;
int n_msgid;
struct my_msg st_msg;
long int l_rec_type;
char sz_buff[BUFFSIZE];
n_msgid = msgget((key_t)1234,0666|IPC_CREAT);
if(n_msgid==-1)
{
fprintf(stderr,"create msg failed: %s!\n",strerror(errno));
exit(EXIT_FAILURE);
}
while(n_run)
{
printf("please input data:");
fgets(sz_buff,BUFFSIZE,stdin);
st_msg.l_msg_type=1;
strcpy(st_msg.sz_msg_text,sz_buff);
//st_msg.sz_msg_text=sz_buff;
if(msgsnd(n_msgid,(void*)&st_msg,MAX_TEXT,0)==-1)
{
fprintf(stderr,"send data error: %s!\n",strerror(errno));
exit(EXIT_FAILURE);
}
if(strncmp(st_msg.sz_msg_text,"end",3)==0)
{
n_run=0;
}
}
exit(EXIT_SUCCESS);
}
msgsnd与msgrec在接受和发送数据类型要注意,不然变异很容易出错
1.传送的类型
2.传送和接收的数据空间