key_t ftok( const char * fname, int id )
用于生成ID值
int msgget(key_t key, int msgflg);
通过key,获取消息队列权限或创建消息队列
int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);
size_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg);发送接收消息函数
以下为创建发送消息的一段代码
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/types.h>
struct msgbuf
{
long type;
char text[256];
};
int main()
{
key_t key;
int ret;
int qid;
struct msgbuf msg;
key = ftok(".", 'a');
printf("key is %d\n", key);
qid = msgget(key,IPC_CREAT|0666);
if(-1 == qid)
{
printf("msgget error\n");
return -1;
}
printf("qid is %d\n", qid);
msg.type = 100;
(void)strcpy(&msg.text, "hello");
ret = msgsnd(qid, &msg, sizeof(msg.text), msg.type);
if(ret < 0)
{
printf("msgsnd error\n");
return -1;
}
return 0;
}
执行上面程序2次后
linux-o45o:~ # ipcs -q
------ Message Queues --------
key msqid owner perms used-bytes messages
0x61122012 0 root 666 512 2
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/types.h>
struct msgbuf
{
long type;
char text[256];
};
int main()
{
key_t key;
int ret;
int qid;
struct msgbuf msg;
key = ftok(".", 'a');
printf("key is %d\n", key);
qid = msgget(key,IPC_CREAT|0666);
if(-1 == qid)
{
printf("msgget error\n");
return -1;
}
printf("qid is %d\n", qid);
msg.type = 100;
ret = msgrcv(qid, &msg, sizeof(msg.text), msg.type, 0);
if(ret < 0)
{
printf("msgrcv error\n");
return -1;
}
printf("msg is %s\n", msg.text);
return 0;
}
执行程序1输出
key is 1628577810
qid is 0
执行程序2输出
key is 1628577810
qid is 0
msg is hello