Inter-Process Communication using Message Passing - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts

Inter-Process Communication using Message Passing

Share This
This is an efficient way of passing a block of data between two unrelated processes. This technique is similar to named pipes, but the major difference is that we don't need to handle opening and closing the pipes. Here, the advantage of this technique over named pipes is that the message queue exists independently of both the sending and receiving processes.

Source code of message_receiver.c
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <unistd.h> #include <sys/msg.h> struct msg_st { long int msg_type; char text[BUFSIZ]; }; int main() { int running = 1; int msgid; struct msg_st data; long int msg_to_receive = 0; msgid = msgget((key_t) 1234, 0666 | IPC_CREAT); if (msgid == -1) { fprintf(stderr, "msgget failed with error: %d\n", errno); exit(EXIT_FAILURE); } while (running) { if (msgrcv(msgid, (void *) &data, BUFSIZ, msg_to_receive, 0) == -1) { fprintf(stderr, "msgrcv failed with error: %d\n", errno); exit(EXIT_FAILURE); } printf("You wrote: %s", data.text); if (strncmp(data.text, "end", 3) == 0) { running = 0; } } if (msgctl(msgid, IPC_RMID, 0) == -1) { fprintf(stderr, "msgctl(IPC_RMID) failed\n"); exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); }
Source code of message_sender.c
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <unistd.h> #include <sys/msg.h> #define MAX_TEXT 512 struct msg_st { long int msg_type; char text[MAX_TEXT]; }; int main() { int running = 1; struct msg_st data; int msgid; char buffer[BUFSIZ]; msgid = msgget((key_t) 1234, 0666 | IPC_CREAT); if (msgid == -1) { fprintf(stderr, "msgget failed with error: %d\n", errno); exit(EXIT_FAILURE); } while (running) { printf("Enter some text: "); fgets(buffer, BUFSIZ, stdin); data.msg_type = 1; strcpy(data.text, buffer); if (msgsnd(msgid, (void *) &data, MAX_TEXT, 0) == -1) { fprintf(stderr, "msgsnd failed\n"); exit(EXIT_FAILURE); } if (strncmp(buffer, "end", 3) == 0) { running = 0; } } exit(EXIT_SUCCESS); }

Happy Exploring!

No comments:

Post a Comment