1 #include <stdio.h> 2 #include <stdlib.h> 3 #include<unistd.h> 4 #include<string.h> 5 #include<sys/types.h> 6 #include<sys/wait.h> 7 8 #include<sys/ipc.h> 9 #include<sys/shm.h> 10 11 int main(int arg ,char *args[]) 12 { 13 14 /* 创建共享文件 15 * int shmid = shmget(IPC_PRIVATE,1024,0666); 16 if(shmid < 0) 17 printf("error "); 18 else 19 printf("success "); 20 */ 21 22 23 24 /* 进程挂载共享文件 25 char* shmbuf; 26 int shmid=0; 27 if(arg>1) 28 { 29 shmid = atoi(args[1]);//通过命令行传递共享内存IP号 30 shmbuf = shmat(shmid,0,0);//附加到共享内存 31 sleep(60); 32 shmdt(shmbuf); 33 } 34 */ 35 char* shmbuf; 36 int shmid=0; 37 if(arg>2) 38 { 39 shmid = atoi(args[1]);//通过命令行传递共享内存IP号 40 shmbuf = shmat(shmid,0,0);//附加到共享内存 41 if(atoi(args[2])==1) //write shared mem 42 { 43 scanf("%s",shmbuf); 44 } 45 if(atoi(args[2])==2)//read shared mem 46 { 47 printf("%s ",shmbuf); 48 } 49 shmdt(shmbuf); 50 } 51 52 return 0; 53 }