该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
#include #include #include #include #include #include #include #include #include
#define A_TYPE 100#define B_TYPE 200
#define LEN (sizeof(struct node) - sizeof(long))
struct node{long type;char mtext[100];};
int child_read(int msg_id){struct node package;
memset(&package,0,sizeof(package));while(1){
if(msgrcv(msg_id,&package,LEN,A_TYPE,0) < 0){perror("fail to msgrcv");exit(-1);}
printf("rcv : %s\n",package.mtext);
if(strncmp(package.mtext,"quit",4) == 0){kill(getppid(),SIGKILL);usleep(1000);exit(-1);}
}
}
int father_write(int msg_id,int pid){char buf[100];struct node package;
memset(buf,0,sizeof(buf));memset(&package,0,sizeof(package));
while(1){
printf(">");fgets(buf,sizeof(buf),stdin);buf[strlen(buf) -1] = 0;
strcpy(package.mtext,buf);package.type = B_TYPE;
if(msgsnd(msg_id,&package,LEN,0) < 0){perror("fail to msgsnd");exit(-1);}
if(strncmp(buf,"quit",4) == 0){kill(pid,SIGKILL);wait(NULL);exit(-1);}}}
int main(){pid_t pid;key_t key;int msg_id;char buf[100];
if((key = ftok(".",'a')) < 0){perror("fail to ftok");exit(-1);}if((msg_id = msgget(key,IPC_CREAT | 0666)) < 0){perror("fail to msgget");}
if((pid = fork()) < 0){perror("fail to fork");exit(-1);}else if(pid == 0){child_read(msg_id);}else{father_write(msg_id,pid);}
return 0;}这上面的是 客户端的