IPC – msg q

Inter Process Communication 

Message Queue


SYSTEM CALL:

Message Queue Send and Receive function:

Prototype   :   int msgsnd ( int msqid, struct msgbuf *msgp, int msgsz, int msgflg);

Parameters :

msqid – queue identifier, returned by a previous call to msgget.

msgp – pointer to redeclared and loaded message buffer.

msgsz – the size of the message in bytes.

RETURNS :   0 on success or -1 on error:

Prototype   :   int msgrcv ( int msqid, struct msgbuf *msgp, int msgsz, long mtype, int msgflg );

Parameters :

msqid – id of the queue to be used during the message retrieval process, returned by an earlier call to msgget.

msgp – address of a message buffer variable to store the retrieved message at.

msgsz – size of the message buffer structure,

mtype – type of message to retrieve from the queue. – The kernel will search the queue for the oldest message having a matching type, and will return a copy of it in the address pointed to by the msgp argument.

Returns :   Number of bytes copied into message buffer, or -1 on error


// Program : 

// 3. IPC Using Message Queue – Sender Program

#include <sys/types.h>

#include <sys/ipc.h>

#include <sys/msg.h>

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

#define MAXSIZE     128

void die(char *s)

{

perror(s);

exit(1);

}

struct msgbuf

{

long    mtype;

char    mtext[MAXSIZE];

};

main()

{

int msqid;

int msgflg = IPC_CREAT | 0666;

key_t key;

struct msgbuf sbuf;

size_t buflen;

key = 1234;

if ((msqid = msgget(key, msgflg )) < 0)

die(“msgget”);

//Message Type

sbuf.mtype = 1;

printf(“Enter a message to add to message queue : “);

scanf(“%[^\n]”,sbuf.mtext);

getchar();

buflen = strlen(sbuf.mtext) + 1 ;

if (msgsnd(msqid, &sbuf, buflen, IPC_NOWAIT) < 0)

{

printf (“%d, %d, %s, %d\n”, msqid, sbuf.mtype, sbuf.mtext, buflen);

die(“msgsnd”);

}

else

printf(“Message Sent\n”);

exit(0);

}


// 3. IPC Using Message Queue – Receiver Program

#include <sys/types.h>

#include <sys/ipc.h>

#include <sys/msg.h>

#include <stdio.h>

#include <stdlib.h>

#define MSGSZ     128

typedef struct msgbuf

{

long    mtype;

char    mtext[MSGSZ];

} message_buf;

main()

{

int msqid;

key_t key;

message_buf  rbuf;

key = 1234;

if ((msqid = msgget(key, 0666)) < 0)

{

perror(“msgget”);

exit(1);

}

if (msgrcv(msqid, &rbuf, MSGSZ, 1, 0) < 0)

{

perror(“msgrcv”);

exit(1);

}

printf(“%s\n”, rbuf.mtext);

exit(0);

}