日期:2014-05-16 浏览次数:20872 次
#ifndef BANK_P_H #define BANK_P_H struct account{ int account_id; char account_name[10]; double account_salary; }; struct Bank{ long mtype; struct account account_m; }; struct Message{ long mtype; char message[20]; }; int key = 0x87111; #endif
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <signal.h> #include "bank_p.h" int msgid; void init()//create message queue { printf("banks' server begins to opened\n"); msgid = msgget(key,IPC_CREAT|IPC_EXCL|0666); if(msgid == -1) msgid = msgget(key,0); if(msgid == -1) perror("banks'server begins to failed"),exit(-1); printf("banks'service successfully\n"); } void service()//receive function { printf("banks' server begins to operation\n"); printf("stop:ctrl+c\n"); struct Bank bank_server; struct Message message_obj; message_obj.mtype = 3; strcpy(message_obj.message,"sorry,can't receive your message comes form linet"); while(1) { //can't receive message ,and send error message to linet. if(msgrcv(msgid,&bank_server,sizeof(struct Bank),1,0)<=0) { if(msgsnd(msgid,&message_obj,sizeof(struct Message),0)== -1) perror("create failed"),exit(-1); printf("send successfully error mesage to client\n"); } } } void show(int signo)//free message queue function { printf("\nbanks'server begins to free\n"); msgctl(msgid,IPC_RMID,0); printf("banks'server has ended\n"); exit(0); } int main() { init(); signal(SIGINT,show); service(); }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include "bank_p.h" int main() { int msgid = msgget(key,0); //send message struct Bank account_client_two; account_client_two.mtype = 2; account_client_two.account_m.account_id = 002; strcpy(account_client_two.account_m.account_name,"Edward"); account_client_two.account_m.account_salary = 1000; if(msgsnd(msgid,&account_client_two,sizeof(struct Bank),0)== -1) perror("send message failed"),exit(1); printf("send message successfully\n"); //receive error message struct Message message_soer; while(1) { if(msgrcv(msgid,&message_soer,sizeof(struct Message),3,0)<=0) perror("No error"),exit(-1); printf("error message:%s\n",message_soer.message); } }