初次编写消息队列程序,错误百出。
用的sunOS5.0+gcc
两个程序互相通信
第一个
ipc_ex1.c
:
#define KEY_MSG 0x101
#define MSGSIZE 128
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
main()
{
int msgid;
struct msgbuf
{
long mtype;
char mtext[128];
} buf1, buf2,bufsign;
msgid = msgget( KEY_MSG, 0666 );
while( 1 )
{ // block
if(gets( buf1.mtext ));
{
buf1.mtype = 2L;
msgsnd( msgid, &buf1, MSGSIZE, 0 );
if( buf1.mtext[0] == 'x ' || buf1.mtext[0] == 'X ' )
break;
msgrcv( msgid, &bufsign, MSGSIZE, 1L, 0 );
printf( "Receive message: %s\n ", bufsign.mtext );
}
if(msgrcv( msgid, &buf2, MSGSIZE, 2L, 0 ));
{
printf( "from2: %s\n ", buf2.mtext );
if( buf2.mtext[0] == 'x ' || buf2.mtext[0] == 'X ' )
break;
bufsign.mtype = 1L;
strcpy( bufsign.mtext, "Received OK " );
msgsnd( msgid, &bufsign, MSGSIZE, 0 );
}
}
}
第二个
ipc_ex2.c
:
#define KEY_MSG 0x101
#define MSGSIZE 128
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
main()
{
int msgid;
struct msgbuf
{
long mtype;
char mtext[128];
} buf1, buf2,bufsign;
msgid = msgget( KEY_MSG, 0666 );
while( 1 )
{ // block
if(gets( buf2.mtext ));
{
buf2.mtype = 2L;
msgsnd( msgid, &buf2, MSGSIZE, 0 );
if( buf2.mtext[0] == 'x ' || buf2.mtext[0] == 'X ' )
break;
msgrcv( msgid, &bufsign, MSGSIZE, 1L, 0 );
printf( "Receive message: %s\n ", bufsign.mtext );
}
if(msgrcv( msgid, &buf1, MSGSIZE, 2L, 0 ));