消息队列可以使用类型来发送和接收消息
key: IPC_PRIVATE, ftok
创建或打开消息队列:msgget
添加消息(发送消息): msgsnd
读取消息(接收消息): msgrcv
控制消息(删除消息队列): msgctl
------------------------------------------------------------------------------
信息队列的创建与添加信息:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
struct msgbuf{
long mtype; //消息类型
char mtext[100]; //消息正文
};
int main(int argc, char *argv[])
{
key_t key = ftok(".", 'b');
if (key < 0)
{
perror("ftok");
return -1;
}
int msgid = msgget(key, IPC_CREAT|0777);
if (msgid < 0)
{
perror("msgget");
return -1;
}
//添加消息
struct msgbuf buf = {1};
while (1)
{
printf("Input type: ");
scanf("%ld", &buf.mtype);
getchar();
printf("Send: ");
fgets(buf.mtext, sizeof(buf.mtext), stdin);
if (0 > msgsnd(msgid, &buf, sizeof(buf)-sizeof(long), 0))
{
perror("msgsnd");
break;
}
if (strncmp(buf.mtext, "quit", 4) == 0)
break;
}
return 0;
}
---------------------------------------------------------------------------
信息队列的读取与删除信息队列:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
struct msgbuf{
long mtype; //消息类型
char mtext[100]; //消息正文
};
int main(int argc, char *argv[])
{
key_t key = ftok(".", 'b');
if (key < 0)
{
perror("ftok");
return -1;
}
int msgid = msgget(key, 0777);
if (msgid < 0)
{
perror("msgget");
return -1;
}
//读取消息
struct msgbuf buf;
while (1)
{
if (0 > msgrcv(msgid, &buf, sizeof(buf)-sizeof(long), 1, 0))
{
perror("msgrcv");
break;
}
printf("recv: %s\n", buf.mtext);
if (strncmp(buf.mtext, "quit", 4) == 0)
break;
}
sleep(1);
if (0 > msgctl(msgid, IPC_RMID, NULL))
{
perror("msgctl");
return -1;
}
return 0;
}