服务器
- #include"sys/types.h"
- #include"sys/msg.h"
- #include"sys/ipc.h"
- #define MSGKEY 75
- struct msgform{
- long mtype;
- char mtext[1000];
- }msg;
- void server()
- {
- int msgid;
- msgid=msgget( MSGKEY, IPC_CREAT | 00666 );/*创建一个消息队列*/
- if(msgid==-1)
- {
- printf("error!\n");
- return;
- }
- do
- {
- if(msgrcv(msgid,(void*)&msg,1000,0,0)==-1)
- {
- printf("receive error!\n");
- exit(0);
- }
- printf("recevied message succeed!\n");
- }while(msg.mtype!=1);
- if(msgctl(msgid,IPC_RMID,0)==-1)
- {
- printf("msgctl failed!\n");
- exit(0);
- }
- exit(1);
- }
- main()
- {
- server();
- }
客户端
- #include"sys/types.h"
- #include"sys/msg.h"
- #include"sys/ipc.h"
- #define MSGKEY 75
- struct msgform
- {
- long mtype;
- char mtext[1000];
- }msg;
- void client()
- {
- int msgid,i;
- msgid=msgget(MSGKEY,IPC_CREAT|00666);
- if(msgid==-1)
- {
- printf("open error!\n");
- return;
- }
- for(i=10;i>=1;i--)
- {
- msg.mtype=i;
- printf("client sent message!\n");
- if(msgsnd(msgid,(void*)&msg,1000,0)==-1)
- {
- printf("send error!\n");
- exit(0);
- }
- printf("send message succeed!\n");
- }
- exit(1);
- }
- main()
- {
- client();
- }