#include<stdio.h>
#include<sys/msg.h>
#define MAX_MSG_BUF_LEN 512
int iKey = 6004;
struct ipcmsgbuf
{
long mtype;
char mtext[MAX_MSG_BUF_LEN];
};
int main( void )
{
int qid;
char sTmp[128], sTmp2[128], sTmp3[128];
struct ipcmsgbuf msgdata;
memset( sTmp, 0, sizeof(sTmp) );
memset( sTmp2, 0, sizeof(sTmp2) );
memset( sTmp3, 0, sizeof(sTmp3) );
if( (qid = msgget(iKey, 0000)) < 0 )
{
printf("0000\n");
qid = msgget( iKey, IPC_CREAT|0660 );
if( qid < 0 )
{
printf( "msgget error!\n" );
return -1;
}
}
/* 写消息队列 */
memset( &msgdata, 0, sizeof( struct ipcmsgbuf ) );
msgdata.mtype = 1;
memcpy( msgdata.mtext, "abcdefg", 7 );
msgsnd( qid, &msgdata, 7, 0 );
/* 写消息队列 */
memset( &msgdata, 0, sizeof( struct ipcmsgbuf ) );
msgdata.mtype = 2;
memcpy( msgdata.mtext, "1234567", 7 );
msgsnd( qid, &msgdata, 7, 0 );
/* 读消息队列 */
memset( &msgdata, 0, sizeof( struct ipcmsgbuf ) );
msgrcv( qid, &msgdata, 7, 1, 0 );
memcpy( sTmp, msgdata.mtext, 7 );
printf( "sTmp=%s\n", sTmp );
/* 读消息队列 */
memset( &msgdata, 0, sizeof( struct ipcmsgbuf ) );
msgrcv( qid, &msgdata, 7, 2, 0 );
memcpy( sTmp2, msgdata.mtext, 7 );
printf( "sTmp2=%s\n", sTmp2 );
/* 读消息队列 */
memset( &msgdata, 0, sizeof( struct ipcmsgbuf ) );
msgrcv( qid, &msgdata, 7, 2, IPC_NOWAIT );
memcpy( sTmp3, msgdata.mtext, 7 );
printf( "sTmp3=%s\n", sTmp3 );
/* 从系统中删除该消息队列以及仍在该队列上的所有数据 */
msgctl( qid, IPC_RMID, 0 );
return 0;
}
运行结果:
0000
sTmp=abcdefg
sTmp2=1234567
sTmp3=
进程间通讯之消息队列