System V Message Queue程序示例——简单C/S通信

msg.h: #include "../../ch06.h" #define MSG1 "../msg1" #define MSG2 "../msg2" client_main.c: #include "../msg.h" extern client(int,int); int main() { int wrmqid = msgget(ftok(MSG1,0),0200);//|IPC_CREAT); int rdmqid = msgget(ftok(MSG2,0),0400);//|IPC_CREAT); if(wrmqid == -1 || rdmqid==-1) perror(""); client(rdmqid,wrmqid); close(rdmqid); close(wrmqid); msgctl(rdmqid,IPC_RMID,NULL); msgctl(wrmqid,IPC_RMID,NULL); exit(0); } client.c: #include "../msg.h" void client(int rd,int wr) { char buf[MAXLINE]={'/0'}; struct msgbuf mbuf; struct msgbuf recvbuf; ssize_t n; bzero(mbuf.mdata,MAXLINE);//注意将发送消息的数据部分初始化 fgets(buf,sizeof(buf),stdin); mbuf.mtype = 100; strcpy(mbuf.mdata,buf); int t; t = msgsnd(wr,&mbuf,sizeof(mbuf)-sizeof(long),0);//注意发送的大小:sizeof(mbuf)-sizeof(long) n = msgrcv(rd,&recvbuf,sizeof(recvbuf)-sizeof(long),0,0); write(STDOUT_FILENO,recvbuf.mdata,n); exit(0); } server_main.c: #include "../msg.h" extern server(int,int); int main() { int rdmqid = msgget(ftok(MSG1,0),0400|IPC_CREAT); int wrmqid = msgget(ftok(MSG2,0),0200|IPC_CREAT);//注意创建消息队列的权限 if(wrmqid == -1) perror(""); server(rdmqid,wrmqid); exit(0); } server.c: #include "../msg.h" void server(int rd,int wr) { int fd; struct msgbuf recvbuf; struct msgbuf sendbuf; char *filename; int n = 0; n = msgrcv(rd,&recvbuf,sizeof(recvbuf)-sizeof(long),100,0); int len = strlen(recvbuf.mdata); filename = (char*)malloc(len+1); strncpy(filename,recvbuf.mdata,len); filename[len]= '/0'; if(filename[len-1]=='/n') filename[len-1]='/0'; fd = open(filename,O_RDONLY,0666); sendbuf.mtype = 100; bzero(sendbuf.mdata,MAXLINE);//发送消息前应将消息数据部分初始化 while((n = read(fd,sendbuf.mdata,MAXLINE))!=0) { msgsnd(wr,&sendbuf,sizeof(recvbuf)-sizeof(long),0);//注意发送消息的大小 } } ch06.h: #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <string.h> #include <sys/stat.h> #include <fcntl.h> #define oops(m,s) {perror(m);exit(s);} #define MAXLINE 1000 /* struct msgbuf { long mtype; int mdata[1]; }; */ struct msgbuf { long mtype; char mdata[MAXLINE]; };

你可能感兴趣的:(struct,server,null,System)