服务器端:
#include <unistd.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <string.h> #define MSGMAX 8000 #define ERR_EXIT(m) \ do \ { \ perror(m); \ exit(EXIT_FAILURE); \ }while(0); \ struct msgbuf { long mtype; /* message type, must be > 0 */ char mtext[MSGMAX]; /* message data */ }; void echo_srv(int msgid) { int n; struct msgbuf msg; memset(&msg,0,sizeof(msg)); while(1) { if( (n = msgrcv(msgid,&msg,MSGMAX,1,0)) < 0) //接受消息 ERR_EXIT("msgrcv"); int pid; pid = *((int*)msg.mtext); //前四个字节是进程ID fputs(msg.mtext+4,stdout); //将接受到的数据打印 msg.mtype = pid; msgsnd(msgid,&msg,n,0); //回射接收到的数据 } } int main(int argc,char *argv[]) { int msgid; //创建一个消息队列 msgid = msgget(1234,IPC_CREAT | 0666); if(msgid == -1) ERR_EXIT("msgget"); echo_srv(msgid); return 0; }
客户端:
#include <unistd.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <string.h> #define ERR_EXIT(m) \ do \ { \ perror(m); \ exit(EXIT_FAILURE); \ }while(0); \ #define MSGMAX 8000 struct msgbuf { long mtype; /* message type, must be > 0 */ char mtext[MSGMAX]; /* message data */ }; void echocli(int msgid) { int pid; int n; pid = getpid(); struct msgbuf msg; memset(&msg,0,sizeof(msg)); msg.mtype = 1; while(fgets(msg.mtext+4,MSGMAX,stdin) != NULL) { *((int*)msg.mtext) = pid; //将pid保存到前四个字节 msg.mtype = 1; if( (msgsnd(msgid,&msg,4+strlen(msg.mtext+4),0)) < 0 ) //发送消息 ERR_EXIT("msgsnd"); memset(msg.mtext+4,0,MSGMAX); if( (n = msgrcv(msgid,&msg,MSGMAX,pid,0)) < 0) //接受回射消息 //ERR_EXIT("msgrcv"); fputs(msg.mtext+4,stdout); memset(msg.mtext+4,0,MSGMAX-4); } } int main(int argc,char *argv[]) { int msgid; msgid = msgget(1234,0); //打开一个消息队列 if (msgid == -1) ERR_EXIT("msgget"); echocli(msgid); return 0; }