Friday, October 10, 2008



Program to sent a message by process p1 and to recieve that message by process p2.

#include

#include

#include

#include

#include

#include

#define MSGSZ 128

/*

* Declare the message structure.

*/

typedef struct msgbuf {

long mtype;

char mtext[MSGSZ];

} message_buf;

main()

{

int pid;

int msqid; // used to store the message queue id.

int msgflg = IPC_CREAT | 0666;

key_t key; // used to store the key for the msg queue.

message_buf sbuf,rbuf; // pointers to the message buffers.

size_t buf_length; // used to store the msg buffer size.

/*

* Get the message queue id for the

* "name" 1234, which was created by

* the server.

*/

key = 1234; // key is assigned a default value.

printf("\nmsgget: Calling msgget(%#lx,\%#o)\n",key, msgflg);

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

perror("msgget");

exit(1);

}

else

printf("msgget: msgget succeeded: msqid = %d\n", msqid);

/*

* We'll send message type 1

*/

sbuf.mtype = 1;

printf("msgget: msgget succeeded: msqid = %d\n", msqid);

(void) strcpy(sbuf.mtext, "Did you get this?");

buf_length = strlen(sbuf.mtext) + 1 ;

/*

* Send a message.

*/

if (msgsnd(msqid, &sbuf, buf_length, IPC_NOWAIT) < 0) {

printf ("%d, %d, %s, %d\n", msqid, sbuf.mtype, sbuf.mtext, buf_length);

perror("msgsnd");

exit(1);

}

else

printf("Message: \"%s\" Sent\n", sbuf.mtext);


/* Create a new process to receive the message */

pid = fork();

if(pid==0)
{

/*

* Receive an answer of message type 1.

*/

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

perror("msgrcv");

exit(1);

}

/*

* Print the answer.

*/

printf("Message recieved :%s\n", rbuf.mtext); 
}



exit(0);

}

No comments: