新闻中心

EEPW首页>嵌入式系统>设计应用> 进程间通信之:消息队列

进程间通信之:消息队列

作者: 时间:2013-09-13 来源:网络 收藏

本文引用地址://m.amcfsurvey.com/article/257123.htm

以下是接收端的代码:

/*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;

/*根据不同的路径和关键字产生标准的key*/

if((key=ftok(.,'a'))==-1)

{

perror(ftok);

exit(1);

}

/*创建*/

if((qid=(key,IPC_CREAT|0666))==-1)

{

perror();

exit(1);

}

printf(Openqueue%dn,qid);

do

{

/*读取*/

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));

/*从系统内核中移走消息队列*/

if((msgctl(qid,IPC_RMID,NULL))0)

{

perror(msgctl);

exit(1);

}

exit(0);

}

以下是程序的运行结果。输入“quit”则两个进程都将结束。

$./msgsnd

Openqueue327680

Entersomemessagetothequeue:firstmessage

Entersomemessagetothequeue:secondmessage

Entersomemessagetothequeue:quit

$./msgrcv

Openqueue327680

Themessagefromprocess6072:firstmessage

Themessagefromprocess6072:secondmessage

Themessagefromprocess6072:quit

linux操作系统文章专题:linux操作系统详解(linux不再难懂)

上一页 1 2 3 下一页

评论


相关推荐

技术专区

关闭