
then when i press the enter button

The first, messagesend.c adds messages to the message queue, and messagercv.c retrieves them.
the code of messagesend.c is
#include stdio.h
#include stdlib.h
#include errno.h
#include sys/types.h
#include sys/ipc.h
#include sys/msg.h
struct my_msgbuf {
long mtype;
char mtext[200];
};
int main(void)
{
struct my_msgbuf buf;
int msqid;
key_t key;
if ((key = ftok("messagesend.c", 'B')) == -1)
{
perror("ftok");
exit(1);
}
if ((msqid = msgget(key, 0644 | IPC_CREAT)) == -1)
{
perror("msgget");
exit(1);
}
printf("Enter lines of text, ^D to quit:\n");
buf.mtype = 1; /* we don't really care in this case */
while(gets(buf.mtext), !feof(stdin))
{
if (msgsnd(msqid, (struct msgbuf *)&buf, sizeof(buf), 0) == -1)
perror("msgsnd");
}
if (msgctl(msqid, IPC_RMID, NULL) == -1)
{
perror("msgctl");
exit(1);
}
return 0;
}
the code of messagerecv.c is
#include stdio.h
#include stdlib.h
#include errno.h
#include sys/types.h
#include sys/ipc.h>
#include sys/msg.h
struct my_msgbuf {
long mtype;
char mtext[200];
};
int main(void)
{
struct my_msgbuf buf;
int msqid;
key_t key;
if ((key = ftok("messagesend.c", 'B')) == -1)
{ /* same key as kirk.c */
perror("ftok");
exit(1);
}
if ((msqid = msgget(key, 0644)) == -1)
{ /* connect to the queue */
perror("msgget");
exit(1);
}
printf("Ready to receive messages.\n");
for(;;)
{ /* Spock never quits! */
if (msgrcv(msqid, (struct msgbuf *)&buf, sizeof(buf), 0, 0) == -1) {
perror("msgrcv");
exit(1);
}
printf("Reciever : \"%s\"\n", buf.mtext);
}
return 0;
}
the output is interesting ..it is fun..try it..
Run two terminals..type the message where u r sending ...and press enter to see what happens in the other terminal..
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.