Sending messages between two processes
The following two programs should run at the same time to
illustrate basic principle of message passing.
The first program creates a message queue and sends one message to
the queue.
The second program reads the message from the queue.
creating and sending
to a simple message queue
The full code listing for message_send.c is as follows:
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <string.h>
#define MSGSZ 128
/* Declare the message structure. */
typedef struct msgbuf {
long mtype;
char mtext[MSGSZ];
} message_buf;
main(){
int msqid;
int msgflg = IPC_CREAT | 0666;
key_t key;
message_buf sbuf;
size_t buf_length;
/* Get the message queue id for the"name" 1234,
which was created bythe server.*/
key = 1234;
if ((msqid = msgget(key, msgflg )) < 0) {
perror("msgget");
exit(1);
}
/* Prepare message type 1*/
sbuf.mtype = 1;
(void) strcpy(sbuf.mtext, "This is my message");
buf_length = strlen(sbuf.mtext) ;
/* Send the message. */
if (msgsnd(msqid, &sbuf, buf_length, IPC_NOWAIT) < 0) {
printf ("Error- message not sent");
exit(1);
}
printf("Message sent" Sent\n");
exit(0);
}
receiving the
above message
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#define MSGSZ 128
/* Declare the message structure */
typedef struct msgbuf {
long mtype;
char mtext[MSGSZ];
} message_buf;
main(){
int msqid;
key_t key;
message_buf rbuf;
/* Get the message queue id for the "name" 1234,
which was created by the server.*/
key = 1234;
if ((msqid = msgget(key, 0666)) < 0) {
perror("msgget");
exit(1);
}
/* Receive an answer of message type 1. */
if (msgrcv(msqid, &rbuf, MSGSZ, 1, 0) < 0) {
perror("message not reedceived");
exit(1);
}
/* Print the answer. */
printf("Received message: %s\n", rbuf.mtext);
exit(0);
}