進(jìn)程間通信之:消息隊(duì)列
以下是消息隊(duì)列接收端的代碼:
/*msgrcv.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;
/*根據(jù)不同的路徑和關(guān)鍵字產(chǎn)生標(biāo)準(zhǔn)的key*/
if((key=ftok(.,'a'))==-1)
{
perror(ftok);
exit(1);
}
/*創(chuàng)建消息隊(duì)列*/
if((qid=msgget(key,IPC_CREAT|0666))==-1)
{
perror(msgget);
exit(1);
}
printf(Openqueue%dn,qid);
do
{
/*讀取消息隊(duì)列*/
memset(msg.msg_text,0,BUFFER_SIZE);
if(msgrcv(qid,(void*)msg,BUFFER_SIZE,0,0)0)
{
perror(msgrcv);
exit(1);
}
printf(Themessagefromprocess%d:%s,msg.msg_type,msg.msg_text);
}while(strncmp(msg.msg_text,quit,4));
/*從系統(tǒng)內(nèi)核中移走消息隊(duì)列*/
if((msgctl(qid,IPC_RMID,NULL))0)
{
perror(msgctl);
exit(1);
}
exit(0);
}
以下是程序的運(yùn)行結(jié)果。輸入“quit”則兩個進(jìn)程都將結(jié)束。
$./msgsnd
Openqueue327680
Entersomemessagetothequeue:firstmessage
Entersomemessagetothequeue:secondmessage
Entersomemessagetothequeue:quit
$./msgrcv
Openqueue327680
Themessagefromprocess6072:firstmessage
Themessagefromprocess6072:secondmessage
Themessagefromprocess6072:quit
linux操作系統(tǒng)文章專題:linux操作系統(tǒng)詳解(linux不再難懂)
評論