/* this program illustrates the use of message passing in UNIX */ #include /* Include files necessary for message passing */ #include #include #include #include /* Include file for waitpid system call */ #define MSG_MODE (MSG_R | MSG_W | IPC_CREAT) /* Set mode bits on message queue */ main() { int msgid, pid; struct mymesg *ptr; /* union wait status; */ int status; struct mymesg { /* Structure definition of messages */ /* that we will pass */ long mtype; char mtext[512]; }; /* System call to create message queue */ if ((msgid = msgget(IPC_PRIVATE,MSG_MODE)) == -1) { printf("Unsuccessful message queue creation \n"); printf("Errno was %d \n",errno); exit(-1); } if ((pid = fork()) != 0) { /* Fork out a child process */ /* This is the parent process */ ptr = (struct mymesg *)malloc(sizeof(struct mymesg)); ptr->mtype = 1; /* Set message type to one */ strcpy(ptr->mtext,"Are you home"); /* System call to send message */ if (msgsnd(msgid,ptr,sizeof(struct mymesg),0) == -1) { printf("Unsuccessful message send \n"); printf("Errno was %d \n",errno); exit(-1); } /* System call to receive a message of type 2 */ if (msgrcv(msgid,ptr,sizeof(struct mymesg),2,0) == -1) { printf("Unsuccessful message send \n"); printf("Errno was %d \n",errno); exit(-1); } printf("Parent: %s\n", ptr->mtext); /* Print the received message */ waitpid (pid, &status, 0); /* System call to destroy message queue */ if (msgctl(msgid,IPC_RMID,0) == -1) { printf ("Error removing message queue.\n"); printf ("Errno was %d.\n", errno); exit(-1); } } else { /* This is the child process */ ptr = (struct mymesg *)malloc(sizeof(struct mymesg)); /* System call to receive a message of type 1 */ if (msgrcv(msgid,ptr,sizeof(struct mymesg),1,0) == -1) { printf("Unsuccessful message send \n"); printf("Errno was %d \n",errno); exit(-1); } printf("Child: %s \n", ptr->mtext); /* Print message received */ sleep(5); /* Sleep for 5 seconds */ ptr->mtype = 2; /* Set message type to 2 */ strcpy(ptr->mtext,"Yes I am home\n"); /* System call to send message */ if (msgsnd(msgid,ptr,sizeof(struct mymesg),0) == -1) { printf("Unsuccessful message send \n"); printf("Errno was %d \n",errno); exit(-1); } } }