Code:
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <string.h>
#define MSGSZ 128
#define mess 122
typedef struct msgbuf {
long mtype;
char mtext[MSGSZ];
} message_buf;
//for reciving structure
typedef struct msg1 {
long type;
char message[mess];
} mess_buf;
main()
{
int msqid;
int msgflg = IPC_CREAT | 0666;
key_t key;
size_t buf_length;
message_buf sbuf;
key = 1234;
// for reciving the data
int msgid;
int msgflag = IPC_CREAT | 0666;
key_t lock;
mess_buf gbuf;
// size_t buffer_length;
lock = 123;
(void) fprintf(stderr, "\nmsgget: Calling msgget(%#lx,%#o)\n",key, msgflg);
if ((msqid = msgget(key, msgflg )) < 0) {
perror("msgget");
exit(1);
}
else
(void) fprintf(stderr,"msgget: msgget succeeded: msqid = %d\n", msqid);
// We'll send message type 1
sbuf.mtype = 1;
(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);
// exit(0);
//this is to recive the message
(void) fprintf(stderr, "\nmsgget: Calling msgget(%#lx,%#o)\n",lock, msgflag);
if ((msgid = msgget(lock, msgflag )) < 0) {
perror("msgget");
exit(1);
}
else
(void) fprintf(stderr,"msgget: msgget succeeded: msqid = %d\n", msgid);
//recive the message form the sender
if (msgrcv(msgid, &gbuf,mess, 1, 0) < 0) {
perror("msgrcv");
exit(1);
}
// Print the answer.
printf("recived:%s\n", gbuf.message);
exit(0);
}
client.c
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#define MSGSZ 128
#define mess 122
typedef struct msgbuf {
long mtype;
char mtext[MSGSZ];
} message_buf;
// for sending structure
typedef struct msg1 {
long type;
char message[mess];
} mess_buf;
main()
{
int msqid;
key_t key;
int msgflg = IPC_CREAT | 0666;
message_buf rbuf;
key = 1234;
// for the tranmission
int msgid;
int msgflag = IPC_CREAT | 0666;
key_t lock;
mess_buf tbuf;
size_t buf_length;
lock = 123;
// reciving starts here
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("msgrcv");
exit(1);
}
printf("%s\n", rbuf.mtext);
// exit(0);
// now we r sending the message to the server
(void) fprintf(stderr, "\nmsgget: Calling msgget(%#lx,\%#o)\n",lock, msgflag);
if ((msgid = msgget(lock, msgflag )) < 0) {
perror("msgget");
exit(1);
}
else
(void) fprintf(stderr,"msgget: msgget succeeded: msqid = %d\n", msgid);
tbuf.type = 1;
(void) strcpy(tbuf.message, "r u hearing me?");
buf_length = strlen(tbuf.message) + 1 ;
// Send a message.
if (msgsnd(msgid, &tbuf, buf_length, IPC_NOWAIT) < 0) {
printf ("%d, %d, %s, %d\n", msgid, tbuf.type, tbuf.message, buf_length);
perror("msgsnd");
exit(1);
}
else
printf("Message: \"%s\" Sent\n", tbuf.message);
exit(0);
}