1#include<unistd.h> 2 #include <sys/types.h> 3 #include <stdio.h> 4 #include <sys/ipc.h> 5 #include <sys/shm.h> 6 #include <stdlib.h> 7 #include <string.h> 8 int main() 9 { 10 int shmid; 11 pid_t ret_fork; 12 shmid = shmget(0,1024,IPC_CREAT|0600); 13 if(shmid == -1) 14 { 15 printf("build shm error\n"); 16 return -1; 17 } 18 ret_fork = fork(); 19 if(ret_fork<0) 20 { 21 printf("error\n"); 22 exit(0); 23 } 24 else if(ret_fork == 0) 25 { 26 char *son_p; 27 son_p = (char *)shmat(shmid,NULL,0);
27 son_p = (char *)shmat(shmid,NULL,0); 28 while(1) 29 { 30 printf("son:"); 31 fflush(stdout); 32 gets(son_p); 33 if(strncmp(son_p,"byebye",6)==0) 34 { 35 shmdt(son_p); 36 exit(0); 37 } 38 39 } 40 } 41 else if(ret_fork > 0) 42 { 43 char *father_p; 44 father_p = (char *)shmat(shmid,NULL,0); 45 while(1) 46 { 47 if(*father_p !='\0') 48 { 49 printf("from son:%s",father_p); 50 if(strncmp(father_p,"byebye",6)==0) 51 { 52 wait(NULL);
53 shmdt(father_p); 54 shmctl(shmid,IPC_RMID,NULL); 55 } 56 memset(father_p,0,1024); 57 } 58 usleep(10); 59 } 60 } 61 62 }
|
1#include<unistd.h> 2 #include <sys/types.h> 3 #include <stdio.h> 4 #include <sys/ipc.h> 5 #include <sys/shm.h> 6 #include <stdlib.h> 7 #include <string.h> 8 int main() 9 { 10 int shmid; 11 pid_t ret_fork; 12 shmid = shmget(0,1024,IPC_CREAT|0600); 13 if(shmid == -1) 14 { 15 printf("build shm error\n"); 16 return -1; 17 } 18 ret_fork = fork(); 19 if(ret_fork<0) 20 { 21 printf("error\n"); 22 exit(0); 23 } 24 else if(ret_fork == 0) 25 { 26 char *son_p; 27 son_p = (char *)shmat(shmid,NULL,0);
27 son_p = (char *)shmat(shmid,NULL,0); 28 while(1) 29 { 30 printf("son:"); 31 fflush(stdout); 32 gets(son_p); 33 if(strncmp(son_p,"byebye",6)==0) 34 { 35 shmdt(son_p); 36 exit(0); 37 } 38 39 } 40 } 41 else if(ret_fork > 0) 42 { 43 char *father_p; 44 father_p = (char *)shmat(shmid,NULL,0); 45 while(1) 46 { 47 if(*father_p !='\0') 48 { 49 printf("from son:%s\n",father_p); 50 if(strncmp(father_p,"byebye",6)==0) 51 { 52 wait(NULL);
53 shmdt(father_p); 54 shmctl(shmid,IPC_RMID,NULL); 55 } 56 memset(father_p,0,1024); 57 } 58 usleep(10); 59 } 60 } 61 62 }
|