進程間通訊IPC-內存共享

函數:多線程

(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

相關文章
相關標籤/搜索