http://www.cs.cf.ac.uk/Dave/C/node25.html
下面是一个利用message queue实现ipc的例子。
要注意的是,当进程退出后,message queue仍然存在。
/*
* =====================================================================================
*
* Filename: message_send.c
*
* Description:
*
* Version: 1.0
* Created: 09/02/2010 02:06:54 PM
* Revision: none
* Compiler: gcc
*
* Author: YOUR NAME (),
* Company:
*
* =====================================================================================
*/
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MSGSZ 128
/*
* Declare the message structure.
*/
typedef struct msgbuf {
long mtype;
char mtext[MSGSZ];
} message_buf;
int
main()
{
int msqid;
// int msgflg = IPC_CREAT | IPC_EXCL | 0666;
int msgflg = IPC_CREAT | IPC_EXCL | 0666;
key_t key;
message_buf sbuf;
size_t buf_length;
/*
* Get the message queue id for the
* "name" 1234, which was created by
* the server.
*/
key = 1234;
fprintf(stderr, "msgget: Calling msgget(%#lx,/%#o)/n", key, msgflg);
if ((msqid = msgget(key, msgflg )) < 0) {
perror("msgget");
exit(1);
}
/*
* We'll send message type 1
*/
sbuf.mtype = 1;
fprintf(stderr,"msgget: msgget succeeded: msqid = %d/n", msqid);
strcpy(sbuf.mtext, "Did you get this?");
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);
}
/*
* =====================================================================================
*
* Filename: message_rec.c
*
* Description:
*
* Version: 1.0
* Created: 09/02/2010 02:13:44 PM
* Revision: none
* Compiler: gcc
*
* Author: YOUR NAME (),
* Company:
*
* =====================================================================================
*/
#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;
int
main()
{
int msqid;
key_t key;
ssize_t msg_size;
message_buf rbuf;
/*
* Get the message queue id for the
* "name" 1234, which was created by
* the server.
*/
key = 1234;
if ((msqid = msgget(key, 0666)) < 0) {
perror("msgget");
exit(1);
}
/*
* Receive an answer of message type 1.
*/
if ( (msg_size = msgrcv(msqid, &rbuf, MSGSZ, 1, 0))< 0) {
perror("msgrcv");
exit(1);
}
/*
* Print the answer.
*/
printf("%d/n%s/n", msg_size, rbuf.mtext);
exit(0);
}