#include <sys/types.h>
#include <sys/msg.h>
#include <unistd.h>
#include<stdio.h>
#include<string.h>
struct msg_buf
{
int mtype;/*标识位*/
char data[255];
};
int main()
{
key_t key;
int msgid;
int ret;
struct msg_buf msgbuf;
key=ftok("/tmp/2",'a');
printf("key =[%x]\n",key);
msgid=msgget(key,IPC_CREAT|0666); /*通过文件对应,获得共享内存区域的ID*/
if(msgid==-1)/*error protect*/
{
printf("create error\n");
return -1;
}
msgbuf.mtype = getpid();/*获得当前进程的pid*/
strcpy(msgbuf.data,"test haha");/*结构体已经被赋值了*/
ret=msgsnd(msgid,&msgbuf,sizeof(msgbuf.data),IPC_NOWAIT);/将结构体发送到消息队列中 *msgid:代表消息队列的名字 &msgbuf:谣传送的消息的内容 sizeof(msgbuf.data)传送内容的长度 当前消息队列没有足够空间容纳新的消息时函数是否等待 成功返回0,否则返回-1*/
if(ret==-1)/*反复送消息失败*/
{
printf("send message err\n");
return -1;
}
/*发送成功*/
memset(&msgbuf,0,sizeof(msgbuf));/*将首地址为&msgbuf一下长度为sizeof(msgbuf)清零*/
ret = msgrcv(msgid, &msgbuf, sizeof(msgbuf.data), msgbuf.mtype,IPC_NOWAIT);/*从msgid代表的消息序列里读取一个消息 并将这个消息写入 &msgbuf为首地址的内存中 sizeof(msgbuf.data)最多可放的长度 msgbuf.mtype请求读取的消息所在的进程类型 IPC_NOWAIT 没有满足的消息类型立刻返回*/
if(ret==-1)
{
printf("recv message err\n");
return -1;
}
printf("recv msg =[%s]\n",msgbuf.data);
}
消息队列
在子进程中写入消息队列,在父进程中读取消息队列
#include <sys/types.h>
#include <sys/msg.h>
#include <sys/ipc.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
struct msg_buf
{
int mtype;
char data[255];
};
int main()
{
key_t key;
pid_t pid;
int msgid;
int ret;
struct msg_buf msgbuf;
key = ftok("/tmp/2",'a');/*获得标准的key值*/
printf("key = [%x]\n",key);
msgid = msgget(key,IPC_CREAT | 6666);/*创建共享内存并返回他的ID*/
if(msgid == -1)
{
printf("error\n");
exit(1);
}
if((pid = fork()) == -1)
{
perror("fork");
}
else if(pid == 0)
{
msgbuf.mtype = getppid();
strcpy(msgbuf.data,"test haha");
ret = msgsnd(msgid,&msgbuf,sizeof(msgbuf.data),IPC_NOWAIT);
if(ret == -1)
{
printf("error\n");
exit(1);
}
memset(&msgbuf,0,sizeof(msgbuf));/*将首地址为&msgbuf一下长度为sizeof(msgbuf)清零*/
}
else/*父进程*/
{
ret = msgrcv(msgid,&msgbuf,sizeof(msgbuf.data),getpid(),IPC_NOWAIT);/*从消息队列中获取消息*/
if(ret == -1)
{
printf("recv message error\n");
exit(1);
}
printf("recv msg %s\n",msgbuf.data);/*获取成功*/
}
}