1、int msgget(key_t key, int flg);
创建队列
key为消息队列的键值,为了找到相应的队列,flg为消息队列的打开方式
返回值:成功返回0,失败返回-1
2、int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);
发送队列
msqid为队列的ID号,*msgp为消息,msgsz为消息的字节大小,msgflg为标志位(口令)
返回值:成功返回0,失败返回-1
3、int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);
接收队列
msqid为队列的ID号,*msgp为消息,msgsz为消息的字节大小,msgflg为标志位(口令)
返回值:成功返回消息数据的长度,失败返回-1
4、int msgctl(int msqid, int cmd, struct msqid_ds *buf);
控制队列
返回值:成功返回0,失败返回-1
发送消息队列
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <string.h>
struct msgbuf{
long mtype;
char mtext[128];
};
int main()
{
//get
struct msgbuf sendbuf = {888,"this is message from que"};
struct msgbuf readbuf;
int msgId = msgget(0x1234,IPC_CREAT|0777); //创建一个队列
if(msgId == -1){
printf("get que failer\n"); //判断返回值
}
msgsnd(msgId,&sendbuf,strlen(sendbuf.mtext),0); //发送队列的数据(sendbuf)
printf("send over\n");
msgrcv(msgId,&readbuf,sizeof(readbuf.mtext),988,0); //接收队列的数据(readbuf)
printf("return from read:%s\n",readbuf.mtext);
return 0;
}
接受消息队列
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <string.h>
struct msgbuf{
long mtype;
char mtext[128];
};
int main()
{
//get
struct msgbuf sendbuf = {988,"thank you for your reach"};
struct msgbuf readbuf;
int msgId = msgget(0x1234,IPC_CREAT|0777); //创建一个队列
if(msgId == -1){
printf("get que failer\n");
} //判断消息队列的返回值
msgrcv(msgId,&readbuf,sizeof(readbuf.mtext),888,0); //接收队列的数据(readbuf)
// msgsnd(msgId,&sendbuf,strlen(sendbuf.mtext),0);
printf("read from que:%s\n",readbuf.mtext);
msgsnd(msgId,&sendbuf,strlen(sendbuf.mtext),0); //发送队列的数据(sendbuf)
return 0;
}