linux 消息队列

时间:2021-11-10 17:53:29

消息队列,这个可是鼎鼎大名,经常在某些地方看见大家那个膜拜,那个,嗯,那个。。。

那就给个完整的例子,大家欣赏就行,我一直认为不用那个,嗯@

这个队列的最大作用就是进程间通信,你要非搞个持久化,那也行,随你高兴喽!

——————————————————————————————————————

// 进程间通信,通过消息队列

//msgqueue-server.c

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <errno.h>

#include <unistd.h>

#include <sys/msg.h>

#include <signal.h>

#define MSG_FILE "/etc/passwd"

struct msg_form

{

long mtype;

char mtext[256];

};

static sig_atomic_t run =1;

void sigint(int signum)

{

if (SIGINT==signum)

{

run = 0;

}

}

int main()

{

signal(SIGINT, sigint);

int msqid;

key_t key;

struct msg_form msg;

int len;

if (0>(key=ftok(MSG_FILE, 'z')))

{

perror("ftok error!\n");

exit(1);

}

printf("MSG -server key is %0x\n", key);

if (-1==(msqid=msgget(key, IPC_CREAT|0777)))

{

perror("msgget error!\n");

exit(1);

}

printf("msqid is %0x\n", msqid);

printf("pid is %0x\n", getpid());

while (run)

{

len = msgrcv(msqid, &msg, 256, 888, IPC_NOWAIT);

if (0<len)

{

printf("MSG -server receive msg type is %0x\n", (unsigned int)msg.mtype);

printf("MSG -server receive msg is %s\n", msg.mtext);

msg.mtype = 999;

sprintf(msg.mtext, "Hello, I'm server %0x\n", getpid());

msgsnd(msqid, &msg, sizeof(msg.mtext), 0);

}

}

printf("MSG -server quit!\n");

if (-1==msgctl(msqid, IPC_RMID, 0))

{

printf("msqid %0x is rmed with error %d %s\n", msqid, errno, strerror(errno));

exit(1);

}

return 0;

}

// msgqueue-client.c

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <errno.h>

#include <unistd.h>

#include <sys/msg.h>

#include <signal.h>

#define MSG_FILE "/etc/passwd"

struct msg_form

{

long mtype;

char mtext[256];

};

int main()

{

int msqid;

key_t key;

struct msg_form msg;

int isnd, len;

if (0>(key=ftok(MSG_FILE, 'z')))

{

perror("ftok error!");

exit(1);

}

printf("MSG -client key is %0x\n", key);

if (-1==(msqid=msgget(key, 0777)))

{

perror("msgget error");

exit(1);

}

printf("msqid is %0x\n", msqid);

printf("pid is %0x\n", getpid());

msg.mtype = 888;

sprintf(msg.mtext, "Hello, I'm client %0x\n", getpid());

isnd = msgsnd(msqid, &msg, sizeof(msg.mtext), IPC_NOWAIT);

if (0==isnd)

{

len = msgrcv(msqid, &msg, 256, 999, 0);

if (0<len)

{

printf("MSG -client receive msg type is %0x\n", (unsigned int)msg.mtype);

printf("MSG -client receive msg is %s\n", msg.mtext);

}

}

return 0;

}

// result

# ./msgqueue-server &
[1] 2588
MSG -server key is 7a011886
msqid is 28000
pid is a1c

# ./msgqueue-client &
[2] 2592
MSG -client key is 7a011886
msqid is 28000
pid is a20
MSG -server receive msg type is 378
MSG -server receive msg is Hello, I'm client a20

MSG -client receive msg type is 3e7
MSG -client receive msg is Hello, I'm server a1c

[2]+ Done ./msgqueue-client

e# jobs
[1]- Running ./msgqueue-server &

# fg 1
./msgqueue-server
^CMSG -server quit!

Finally:

用好了,还是挺强大的啊