函数:多线程
(1)int shmget(key_t key, int size, int shmflg),开辟或使用一块共享内存。函数
(2)void *shmat(int shmid, const void *shmaddr, int shmflg), 将参数shmid所指向的共享内存与当前进程链接。当使用某共享内存时,须要先使用shmat,达成链接。spa
(3)int shmdt(const void *shmaddr),将先前用shmat链接的共享内存与当前进程解除链接。参数shmaddr为shmat返回的共享内存的地址。在完成对共享内存的使用后,须要使用shmdt解除链接。.net
(4)int shmctl(int shmid, int cmd, struct shmid_ds *buf),控制内存的操做。当cmd为IPC_RMID时,删除shmid所指的共享内存。线程
实例:code
1 file: shmshare.c 2 #include<stdio.h> 3 #include<stdlib.h> 4 #include<errno.h> 5 #include<sys/ipc.h> 6 #include<sys/shm.h> 7 8 int main(int argc, char* argv[]) 9 { 10 int shmid = shmget(IPC_PRIVATE, 1024, IPC_CREAT | 0666); 11 if (shmid < 0) 12 { 13 perror("shmget"); 14 exit(EXIT_FAILURE); 15 } 16 printf("create shared memory OK, size = 1024, shmid = %d\n", shmid); 17 18 char* buff = (char*)shmat(shmid, NULL, 0); 19 if ((int)buff == -1) 20 { 21 perror("shmat"); 22 exit(EXIT_FAILURE); 23 } 24 memset(buff, 0, 1024); 25 char temp[1024] = ""; 26 scanf("%s", temp); 27 strncpy(buff, temp, 1024); 28 29 shmctl(shmid, IPC_RMID, NULL); 30 return 0; 31 }
1 file: shmshare2.c 2 #include<stdio.h> 3 #include<stdlib.h> 4 #include<errno.h> 5 #include<sys/ipc.h> 6 #include<sys/shm.h> 7 #include<assert.h> 8 9 int main(int argc, char* argv[]) 10 { 11 assert(argc == 2); 12 int shmid = atoi(argv[1]); 13 char* buff = (char*)shmat(shmid, NULL, 0); 14 if ((int)buff == -1) 15 { 16 perror("shmat"); 17 exit(EXIT_FAILURE); 18 } 19 while(1) 20 { 21 if (buff[0]) 22 { 23 printf("buff:%s\n", buff); 24 break; 25 } 26 } 27 shmdt(buff); 28 return 0; 29 }
1 $gcc -Wall -o shmshare shmshare.c 2 $./shmshare 3 create shared memory OK, size = 1024, shmid = 229377 4 <wait for input>
1 $gcc -Wall -o shmshare2 shmshare2.c 2 $./shmshare2 229377 3 print <wait for input>
总结:共享内存是各类通讯方式中效率最高的,可是也有一些问题,如多进程,多线程访问共享内存时同步问题。各类通讯方式大同小易,原理都差很少,都是由系统提供支持的通讯方式。从消息队列,信号量能够看出,这系列POSIX IPC的方式是相似,查看man手册能够了解到更多的用法。blog