#include <stdio.h> #include <sys/types.h> #include <sys/msg.h> #include <sys/ipc.h> #define MSGKEY 75 /*定义关键词MEGKEY*/ struct msgform /*消息结构*/ { long mtype; char mtexe[100]; /*文本长度*/ }msg; int msgqid,i; void CLIENT( ) { int i; msgqid=msgget(MSGKEY,0777|IPC_CREAT); for(i=10;i>=1;i--) { msg.mtype=i; printf("(client)sent\n"); msgsnd(msgqid,&msg,1030,0); /*发送消息msg入msgid消息队列*/ } exit(0); } void SERVER( ) { msgqid=msgget(MSGKEY,0777|IPC_CREAT); /*由关键字获得消息队列*/ do { msgrcv(msgqid,&msg,1030,0,0); /*从队列msgid接受消息msg*/ printf("(server)receive\n"); }while(msg.mtype!=1); /*消息类型为1时,释放队列*/ msgctl(msgqid, IPC_RMID,0); } main() { if(fork()) { SERVER(); wait(0); } else CLIENT( ); }
结果截图:
#include<sys/types.h> #include<sys/msg.h> #include<sys/ipc.h> #define SHMKEY 75 /*定义共享区关键词*/ int shmid,i; int *addr; CLIENT() { int i; shmid=shmget(SHMKEY,1024, 0777|IPC_CREAT); /*获取共享区,长度1024,关键词SHMKEY*/ addr=shmat(shmid,0,0); /*共享区起始地址为addr*/ for(i=9;i>=0;i--) { while(*addr!= -1); printf("(client)sent\n"); /*打印(client)sent*/ *addr=i; /*把i赋给addr*/ } exit(0); } SERVER() { do { while(*addr = =-1); printf("(server)received\n%d",*addr); /*服务进程使用共享区*/ if(*addr!=0) *addr=-1; } while(*addr); wait(0); shmctl(shmid,IPC_RMID,0); } main() { shmid=shmget(SHMKEY,1024,0777|IPC_CREAT); /*创建共享区*/ addr=shmat(shmid,0,0); /*共享区起始地址为addr*/ *addr=-1; if(fork()) { SERVER(); } else { CLIENT(); } }
运行结果: