message_send.c
#include<unistd.h>
#include<stdlib.h>#include<stdio.h>
#include<string.h>
#include<errno.h>
#include<sys/msg.h>
#define MAX_TEXT 512
struct msg_st
{
long int msg_type;
char text[MAX_TEXT];
};
int main()
{
int runing =1;
struct msg_st data;
char buffer[BUFSIZ];
int msgid=-1;
msgid=msgget((key_t)1234,0666 | IPC_CREAT);
if(msgid==-1)
{
fprintf(stderr,"msgget failed with error: \n");
exit(EXIT_FAILURE);
}
while(runing)
{
printf("Please Enter some text:");
fgets(buffer,BUFSIZ,stdin);
data.msg_type=1;
strcpy(data.text,buffer);
if(msgsnd(msgid,(void*)&data,MAX_TEXT,0)==-1)
{
fprintf(stderr,"msgsend failed \n");
exit(EXIT_FAILURE);
}
if(strncmp(buffer,"end",3)==0) runing=0;
sleep(1);
}
exit(EXIT_SUCCESS);
}
message_get.c
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<errno.h>
#include<sys/msg.h>
struct msg_st
{
long int msg_type;
char text[BUFSIZ];
};
int main()
{
int running=1;
int msgid=-1;
struct msg_st data;
long int msgtype=0;
msgid=msgget((key_t)1234,0666 | IPC_CREAT);
if(msgid==-1)
{
fprintf(stderr,"message failed with error: %d \n",errno);
exit(EXIT_FAILURE);
}
while(running)
{
if(msgrcv(msgid,(void*)&data,BUFSIZ,msgtype,0)==-1)
{
fprintf(stderr,"msgrcv failed with erron: %d \n",errno);
exit(EXIT_FAILURE);
}
printf("You wrote:%s\n",data.text);
if(strncmp(data.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);
}