Skip to content

Instantly share code, notes, and snippets.

@hirokuma
Created May 25, 2017 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hirokuma/5916e918f40bbf82dc5723e42789007c to your computer and use it in GitHub Desktop.
Save hirokuma/5916e918f40bbf82dc5723e42789007c to your computer and use it in GitHub Desktop.
linux msgsnd() max
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <unistd.h>
#define FTOK_FNAME "msgq.dat"
#define FTOK_CHAR 'b'
#define SZ_BUF (8192)
struct my_msgbuf {
long mtype;
char mtext[SZ_BUF + 256];
};
static int msg_send(void)
{
struct my_msgbuf buf;
int msqid;
key_t key;
if ((key = ftok(FTOK_FNAME, FTOK_CHAR)) == -1) {
perror("ftok");
exit(1);
}
if ((msqid = msgget(key, 0644 | IPC_CREAT)) == -1) {
perror("msgget");
exit(1);
}
printf("send after 5sec...\n");
sleep(5);
buf.mtype = 1;
memset(buf.mtext, 0x77, SZ_BUF + 256);
if (msgsnd(msqid, &buf, SZ_BUF, 0) == -1) {
perror("msgsnd");
}
if (msgctl(msqid, IPC_RMID, NULL) == -1) {
perror("msgctl");
exit(1);
}
return 0;
}
static int msg_recv(void)
{
struct my_msgbuf buf;
int msqid;
key_t key;
if ((key = ftok(FTOK_FNAME, FTOK_CHAR)) == -1) {
perror("ftok");
exit(1);
}
if ((msqid = msgget(key, 0644)) == -1) {
perror("msgget");
exit(1);
}
memset(buf.mtext, 0xcc, SZ_BUF + 256);
if (msgrcv(msqid, &buf, SZ_BUF, 0, 0) == -1) {
perror("msgrcv");
exit(1);
}
for (int lp = 0; lp < SZ_BUF + 256; lp++) {
if (buf.mtext[lp] != 0x77) {
printf("mismatch at %d !\n", lp);
break;
}
}
return 0;
}
int main(int argc, char *argv[])
{
switch (argv[1][0]) {
case '0':
msg_send();
break;
case '1':
msg_recv();
break;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment