程序也就是这么个程序,能够实现进程间通讯,自己也是费了不少功夫想出来的,感觉设计确实是比实现复杂不少。
发到这里当个备份吧。
 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <unistd.h>
 4 #include <string.h>
 5 #include <sys/ipc.h>
 6 #include <sys/msg.h>
 7 #define size 512
 8 struct msg{
 9     int sign;    int a1;        int a2;
10     char message[size];
11 }mymsg;
12 int main(){
13     int pid;
14     char name[size];
15     int id;
16     printf("please input the name:\n");
17     fgets(name,size,stdin);
18     id=getpid();
19     int sid=msgget(9967,0777|IPC_CREAT);
20     mymsg.a1=id;
21     mymsg.sign=1;
22     strcpy(mymsg.message,name);
23     if(msgsnd(sid,&mymsg,size,0)==-1){
24         perror("msgsnd");
25         exit(1);
26     }
27 
28     pid=fork();
29     if(pid==0){
30         int lid=msgget(id,0777|IPC_CREAT);
31         while(1){
32             if(msgrcv(lid,&mymsg,size,0,0)==-1){
33                 perror("msgrcv");
34                 exit(1);
35             }
36             if(mymsg.sign==1){
37                 printf("%d : %s",mymsg.a1,mymsg.message);
38             }else if(mymsg.sign==2){
39                 printf("id=%d , name=%s",mymsg.a1,mymsg.message);
40             }else if(mymsg.sign==5){
41                 printf("warning : no such user online!!!!!!\n");
42             }
43         }
44     }else{
45         int sid=msgget(9967,0777|IPC_CREAT);
46         int sign1;
47         while(1){
48             printf("input 2 for get the info of login.\n");
49             printf("input 3 for send the message to somebody\n");
50             printf("input 4 for quit\n");
51             scanf("%d",&sign1);
52             if(sign1==2){
53                 mymsg.sign=2;
54                 mymsg.a1=id;
55                 if(msgsnd(sid,&mymsg,size,0)==-1){
56                     perror("msgsnd");
57                     exit(1);
58                 }
59             }else if(sign1==3){
60                 mymsg.sign=3;
61                 mymsg.a1=id;
62                 printf("please input the id you want to send to:\n");
63                 scanf("%d",&mymsg.a2);
64                 getchar();
65                 printf("please input the message:\n");
66                 fgets(mymsg.message,size,stdin);
67                 if(msgsnd(sid,&mymsg,size,0)==-1){
68                     perror("msgsnd");
69                     exit(1);
70                 }
71             }else if(sign1==4){
72                 mymsg.sign=4;
73                 mymsg.a1=id;
74                 printf("goodbye~\n");
75                 if(msgsnd(sid,&mymsg,size,0)==-1){
76                     perror("msgsnd");
77                     exit(1);
78                 }
79                 exit(1);
80             }
81             
82         }
83     }
84     return 0;
85 }
86 
87 
88 
89 
90 
91             
92     
客户端程序

相关文章: