Created
May 12, 2023 19:43
-
-
Save oscarkramer/30d9f88b22260f1eb8b37549b2057737 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// C Program for IPC Message Queue. Adapted from https://www.geeksforgeeks.org/ipc-using-message-queues/ | |
#include <stdio.h> | |
#include <sys/ipc.h> | |
#include <sys/msg.h> | |
#include <cstring> | |
using namespace std; | |
// structure for message queue | |
struct mesg_buffer { | |
long mtype; | |
char mtext[100]; | |
}; | |
int main(int argc, char** argv) | |
{ | |
if (argc < 2) | |
{ | |
cout<<"Need argument to be 'xmt' or 'rcv'"<<endl; | |
return 1; | |
} | |
string xr = argv[1]; | |
// Any int between 0x01 and 0xff: | |
int id = 69; | |
// Must exist in the filesystem. Not clear what the point is here: | |
const char* pathname = "dummy.txt"; | |
// ftok to generate unique key | |
key_t key = ftok(pathname, id); | |
if (key < 0) | |
{ | |
printf("Bad key!\n"); | |
return 1; | |
} | |
// msgget creates a message queue and returns identifier | |
int msgid = msgget(key, 0666 | IPC_CREAT); | |
mesg_buffer message; | |
if (xr == "xmt") | |
{ | |
// msgsnd to send message and echo to console: | |
message.mtype = 1; | |
strcpy(message.mtext, "Hello Process!"); | |
msgsnd(msgid, &message, sizeof(message), 0); | |
printf("Data send is : %s \n", message.mtext); | |
} | |
else | |
{ | |
// msgrcv to receive message then destroy queue: | |
msgrcv(msgid, &message, sizeof(message), 1, 0); | |
printf("Data Received is : %s \n", message.mtext); | |
msgctl(msgid, IPC_RMID, NULL); | |
} | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example of xmt/rcv interprocess message queuing. Run as two separate instances: