进程间通信之:消息队列
表8.26列举了msgctl()函数的语法要点。
表8.26 msgctl()函数语法要点
所需头文件 | #includesys/types.h> #includesys/ipc.h> #includesys/shm.h> | |
函数原型 | intmsgctl(intmsgqid,intcmd,structmsqid_ds*buf) | |
函数传入值 | msqid:消息队列的队列ID | |
cmd: 命令参数 | IPC_STAT:读取消息队列的数据结构msqid_ds,并将其存储在buf指定的地址中 | |
IPC_SET:设置消息队列的数据结构msqid_ds中的ipc_perm域(IPC操作权限描述结构)值。这个值取自buf参数 | ||
IPC_RMID:从系统内核中删除消息队列 | ||
buf:描述消息队列的msgqid_ds结构类型变量 | ||
函数返回值 | 成功:0 | |
出错:-1 |
3.使用实例
这个实例体现了如何使用消息队列进行两个进程(发送端和接收端)之间的通信,包括消息队列的创建、消息发送与读取、消息队列的撤消和删除等多种操作。
消息发送端进程和消息接收端进程之间不需要额外实现进程之间的同步。在该实例中,发送端发送的消息类型设置为该进程的进程号(可以取其他值),因此接收端根据消息类型确定消息发送者的进程号。注意这里使用了函数fotk(),它可以根据不同的路径和关键字产生标准的key。以下是消息队列发送端的代码:
/*msgsnd.c*/
#includesys/types.h>
#includesys/ipc.h>
#includesys/msg.h>
#includestdio.h>
#includestdlib.h>
#includeunistd.h>
#includestring.h>
#defineBUFFER_SIZE512
structmessage
{
longmsg_type;
charmsg_text[BUFFER_SIZE];
};
intmain()
{
intqid;
key_tkey;
structmessagemsg;
/*根据不同的路径和关键字产生标准的key*/
if((key=ftok(.,'a'))==-1)
{
perror(ftok);
exit(1);
}
/*创建消息队列*/
if((qid=msgget(key,IPC_CREAT|0666))==-1)
{
perror(msgget);
exit(1);
}
printf(Openqueue%dn,qid);
while(1)
{
printf(Entersomemessagetothequeue:);
if((fgets(msg.msg_text,BUFFER_SIZE,stdin))==NULL)
{
puts(nomessage);
exit(1);
}
msg.msg_type=getpid();
/*添加消息到消息队列*/
if((msgsnd(qid,msg,strlen(msg.msg_text),0))0)
{
perror(messageposted);
exit(1);
}
if(strncmp(msg.msg_text,quit,4)==0)
{
break;
}
}
exit(0);
}
linux操作系统文章专题:linux操作系统详解(linux不再难懂)
评论