(注)源代码还要再修改才能运行
头文件
#define MSGKEY 1183
struct msgform {
long mtype;
int source_pid;
double a,b;
char opcode;
double result;
char result_msg[128];
}msg;
int msgsize=sizeof(struct msgform)-sizeof(long);
int msgqid;
server.c
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <msg_mycs.h>
main()
{
int i;
extern cleanup();
for(i=0;i<20;i++)
signal(i,cleanup);
msgqid = msgget(MSGKEY,0777|IPC_CREAT);
for(;msg.opcode!='q';)
{
printf("server pid= %d is ready (msgqid=%d)...
",getpid(),msgqid);
msgrcv(msgqid,&msg,msgsize,1,0);
printf("server: receive from pid=%d
",msg.source_pid);
msg.result_msg[0]='1';
switch(msg.opcode){
case '+':
msg.result=msg.a+msg.b;
break;
case '-':
msg.result=msg.a-msg.b;
break;
case '*':
msg.result=msg.a*msg.b;
break;
case '/':
if(msg.b!=0)
msg.result=msg.a/msg.b;
else
strcpy(msg.result_msg,"0. divide by 0.");
break;
default:
strcpy(msg.result_msg,"0. exit by user.") ;
break;
}
if(msg.result_msg[0]=='1')
printf("%.2f %c %.2f = %.2f
",msg.a,msg.opcode,msg.b,msg.result);
else
printf("%s
",msg.result_msg);
msg.mtype=msg.source_pid;
msg.source_pid=getpid();
msgsnd(msgqid,&msg,msgsize,0);
}
printf("server exit by client pid=%d
",msg.mtype);
}
cleanup()
{
msgctl(msgqid,IPC_RMID,0);
exit(0);
}
client.c
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <msg_mycs.h>
main()
{
struct msgform msg;
int pid;
msgqid = msgget(MSGKEY,0777);
pid=getpid();
for(;msg.opcode!='q';){
printf("a=");
scanf("%lf",&msg.a);
printf("b=");
scanf("%lf",&msg.b);
printf("opcode=(+,-,*,/,q for EXIT)");
msg.opcode=getchar();
while(msg.opcode=='
')msg.opcode=getchar();
if(msg.opcode=='+'||msg.opcode=='-'||'*'==msg.opcode ||
'/'==msg.opcode||'q'==msg.opcode)
{
msg.source_pid=pid;
msg.mtype=1;
msg.result_msg[0]=0;
msgsnd(msgqid,&msg,msgsize,0);
msgrcv(msgqid,&msg,msgsize,pid,0);
printf("client: receive from pid=%d
",msg.source_pid);
if(msg.result_msg[0]=='1')
printf("%.2f %c %.2f = %.2f
",msg.a,msg.opcode,msg.b,msg.result);
else
printf("%s
",msg.result_msg);
}
}
}