Skip to content

Instantly share code, notes, and snippets.

@Mark-htmlgogogo
Created December 29, 2017 09:05
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mark-htmlgogogo/e024c36541646373581472348657304d to your computer and use it in GitHub Desktop.
Save Mark-htmlgogogo/e024c36541646373581472348657304d to your computer and use it in GitHub Desktop.
Example: Sending messages between two processes using msgsnd() and msgrcv() Source: https://users.cs.cf.ac.uk/Dave.Marshall/C/node25.html
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#define MSGSZ 128
// Declare the message structure.
typedef struct msgbuf {
long mtype;
char mtext[MSGSZ];
} message_buf;
main()
{
int msqid;
key_t key;
message_buf rbuf;
key = 2234;
if ((msqid = msgget(key, 0666)) < 0) {
perror("msgget");
exit(1);
}
// Receive an answer of message type 1.
if (msgrcv(msqid, &rbuf, MSGSZ, 1, 0) < 0) {
perror("msgrcv");
exit(1);
}
printf("^%s\n", rbuf.mtext);
exit(0);
}
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MSGSZ 128
// Declare the message structure
typedef struct msgbuf {
long mtype;
char mtext[MSGSZ];
} message_buf;
main()
{
int msqid;
int msgflg = IPC_CREAT | 0666;
key_t key;
message_buf sbuf;
size_t buf_length;
key = 2234;
(void)fprintf(stderr, "\nmsgget: Calling msgget(%#1x,\%#o)\n", key, msgflg);
if ((msqid = msgget(key, msgflg)) < 0) {
perror("msgget");
exit(1);
}
else
(void)fprintf(stderr, "msgget: msgget succeeded: msgqid = %d\n", msqid);
// We'll send message type 1
sbuf.mtype = 1;
(void) fprintf(stderr, "msggeet: msgget succeeded: msqid = %d\n", msqid);
(void) strcpy(sbuf.mtext, "Did you get this?");
(void) fprintf(stderr, "msgget: msgget succeeded: msqid = %d\n", msqid);
buf_length = strlen(sbuf.mtext) + 1;
// Send a message.
if((msgsnd(msqid, &sbuf, buf_length, IPC_NOWAIT)) < 0){
printf("%d, %d, %s, %d\n", msqid, sbuf.mtype, sbuf.mtext, buf_length);
perror("msgsnd");
exit(1);
}
else
printf("Message: \"%s\" Sent\n", sbuf.mtext);
exit(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment