//msg_send.c
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/msg.h>
#define TEXT_SIZE 128
/* for sender */
struct my_msg_st{
long int my_msg_type;
char text[TEXT_SIZE];
};
int main(){
int running = 1;
int msg_id;
struct my_msg_st msg_data;
long int msg_to_rcv_tag = 0;
char text[TEXT_SIZE] = {0};
/*1. establish msg queue*/
msg_id = msgget((key_t)1234, 0666|IPC_CREAT);
if(-1 == msg_id){
fprintf(stderr, "[SEND] msgget failed\n"); exit(EXIT_FAILURE);
}
/* 2. send msg to msg queue*/
while(running){
printf("Enter some text...\n");
fgets(text, TEXT_SIZE, stdin);
msg_data.my_msg_type = 1;
strcpy(msg_data.text, text);
if(msgsnd(msg_id, (void*)&msg_data, TEXT_SIZE, 0) == -1){
fprintf(stderr, "msgsnd failed with error:%d\n", errno); exit(EXIT_FAILURE);
}
printf("[SEND]:%s\n", msg_data.text);
if(strncmp(msg_data.text, "end", 3)==0){
running = 0;
}
}
/*3. delete msg queue*/
if(msgctl(msg_id, IPC_RMID, 0) ==-1){
fprintf(stderr, "[SEND] msgctl(IPC_RMID) failed\n");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
//msg_rcv.c
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/msg.h>
#define TEXT_SIZE 128
/* for recver */
struct my_msg_st{
long int my_msg_type;
char text[TEXT_SIZE];
};
int main(){
int running = 1;
int msg_id;
struct my_msg_st msg_data;
long int msg_to_rcv_tag = 0;
/*1. establish msg queue*/
msg_id = msgget((key_t)1234, 0666|IPC_CREAT);
if(-1 == msg_id){
fprintf(stderr, "[RCV] msgget failed\n"); exit(EXIT_FAILURE);
}
/* 2. recv msg from msg queue*/
while(running){
if(msgrcv(msg_id, (void*)&msg_data, TEXT_SIZE, msg_to_rcv_tag, 0) == -1){
fprintf(stderr, "msgrcv failed with error:%d\n", errno); exit(EXIT_FAILURE);
}
printf("[RCV]:%s\n", msg_data.text);
if(strncmp(msg_data.text, "end", 3)==0){
running = 0;
}
}
/*3. delete msg queue*/
if(msgctl(msg_id, IPC_RMID, 0) ==-1){
fprintf(stderr, "[RCV] msgctl(IPC_RMID) failed\n");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}