Skip to content

Instantly share code, notes, and snippets.

@bibstha
Created November 17, 2020 21:51
Show Gist options
  • Save bibstha/dd842dc5c3ef7d144fd78d1862a7f8f2 to your computer and use it in GitHub Desktop.
Save bibstha/dd842dc5c3ef7d144fd78d1862a7f8f2 to your computer and use it in GitHub Desktop.
sysv message queue send and receive example.
// Playing around with sysv message queue
// This program will
// 1. Create a sysv message queue
// 2. Send messages
// 3. Receive messages
// How to run
// touch /tmp/c.txt <- this file is necessary for ftok to run.
// gcc -o mq message_queue.c
// ./mq send <- sends random long each time it is executed
// ./mq receive <- receives the values in the queue and displays them one at a time, oldest first.
#include "sys/msg.h"
#include "sys/ipc.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "time.h"
struct databag {
long mtype;
double salary;
char name[5];
};
int msgsz = sizeof(struct databag) - sizeof(long);
int mtype = 10;
int get_qid(key_t keyval) {
int qid;
qid = msgget(keyval, IPC_CREAT | 0660);
if (qid == -1) {
return -1;
} else {
return qid;
}
}
int send_message(int qid, struct databag *msg) {
printf("Sending message\n");
int ret = msgsnd(qid, msg, msgsz, 0);
if (ret == -1) {
perror("msgsnd error");
exit(1);
}
return ret;
}
int receive_message(int qid, struct databag *msg) {
printf("Receiving message\n");
int ret = msgrcv(qid, msg, msgsz, mtype, IPC_NOWAIT);
if (ret == -1) {
perror("msgrcv error");
exit(1);
}
return ret;
}
int main(int argc, char* argv[]) {
char file_path[] = "/tmp/c.txt";
key_t keyval = ftok(file_path, 'A');
printf("keyval in hex=%x\n", keyval);
int qid = get_qid(keyval);
if (qid == -1) {
perror("msgget failed");
exit(1);
}
printf("msgget success: queue qid is %d \n", qid);
if (argc > 1 && !strcmp(argv[1], "receive")) {
struct databag rcvmsg;
receive_message(qid, &rcvmsg);
printf("Name %s has salary is %f\n", rcvmsg.name, rcvmsg.salary);
}
if (argc > 1 && ~strcmp(argv[1], "send")) {
srand(time(0));
struct databag sndmsg;
sndmsg.mtype = mtype;
sndmsg.salary = rand();
strcpy(sndmsg.name, "JACK");
printf("new salary is %f\n", sndmsg.salary);
send_message(qid, &sndmsg);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment