消息队列提供了一种从一个进程向另一个进程发送数据块的方法。
每个数据块都存在一个类型,接收进程可以独立地接收含有不同类型的数据。
可通过发送消息来避免有名管道的同步和阻塞问题。消息队列与有名管道一样,每个数据块都有长度限制
编译环境:Linux 10.04 LTS GCC
#include <sys/msg.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <stdio.h>
#include <string.h>
#include <sys/errno.h>
extern int errno;
struct mymsgbuf /* 定义消息结构 */
{
long mtype; /* 消息类型 */
char ctext[100]; /* 消息数据 */
};
int main()
{
struct mymsgbuf buf; /* 申请消息缓冲 */
int msid;
int pid;
int ret;
/* 打开(或创建)消息队列 */
if ((msid = msgget(0x1234, 0666|IPC_CREAT)) < 0)
{
fprintf(stderr, "open msg %X failed.\n", 0x1234);
return ;
}
pid = fork();
if (pid < 0)
{
perror("fork");
return;
}
if (pid > 0)
{
while(1)
{
memset(&buf, 0,