Linux代码实操——共享内存

共享内存原理

  • 共享内存为多个进程之间共享和传递数据提供了一种有效的方式。共享内存是先在物理内存上申请一块空间,多个进程可以将其映射到自己的虚拟地址空间中。
  • 所有进程都可以访问共享内存中的地址,就好像它们是由 malloc 分配的一样。如果某个进程向共享内存写入了数据,所做的改动将立刻被可以访问同一段共享内存的任何其他进程看到。
  • 由于它并未提供同步机制,所以我们通常需要用其他的机制来同步对共享内存的访问。

 

 共享内存示例代码实操:

1. #include <sys/ipc.h>
2. #include <sys/shm.h>
3. #include <sys/types.h>
4.
5. /*
6. shmget()用于创建或者获取共享内存
7. shmget()成功返回共享内存的 ID, 失败返回-1
8. key: 不同的进程使用相同的 key 值可以获取到同一个共享内存
9. size: 创建共享内存时,指定要申请的共享内存空间大小
10. shmflg: IPC_CREAT IPC_EXCL
11. */
12. int shmget(key_t key, size_t size, int shmflg);
13.
14. /*
15. shmat()将申请的共享内存的物理内存映射到当前进程的虚拟地址空间上
16. shmat()成功返回返回共享内存的首地址,失败返回 NULL
17. shmaddr:一般给 NULL,由系统自动选择映射的虚拟地址空间
18. shmflg: 一般给 0, 可以给 SHM_RDONLY 为只读模式,其他的为读写
19. */
20. void* shmat(int shmid, const void *shmaddr, int shmflg);
21.
22. /*
23. shmdt()断开当前进程的 shmaddr 指向的共享内存映射
24. shmdt()成功返回 0, 失败返回-1
25. */
26. int shmdt(const void *shmaddr);
27.
28. /*
29. shmctl()控制共享内存
30. shmctl()成功返回 0,失败返回-1
31. cmd: IPC_RMID
32. */
33. int shmctl(int shmid, int cmd, struct shmid_ds *buf);

下面我们来编写代码实现:进程 a 向共享内存中写入数据,进程 b 从共享内存中读取数据并显示

shma.c 的代码:
1. #include<stdio.h>
2. #include<stdlib.h>
3. #include<unistd.h>
4. #include<string.h>
5. #include<assert.h>
6. #include <sys/ipc.h>
7. #include <sys/shm.h>
8. #include <sys/types.h>
9.
10. int main()
11. {
12. int shmid = shmget((key_t)1234, 128, IPC_CREAT | 0600);
13. assert( shmid != -1 );
14.
15. char *s = (char *)shmat(shmid, NULL, 0);
16. assert( s != NULL );
17.
18. strcpy(s, "hello");
19.
20. shmdt(s);
21. exit(0);
22. }

 

shmb.c 的代码:

 

1. #include<stdio.h>
2. #include<stdlib.h>
3. #include<unistd.h>
4. #include<string.h>
5. #include<assert.h>
6. #include <sys/ipc.h>
7. #include <sys/shm.h>
8. #include <sys/types.h>
9.
10. int main()
11. {
12. int shmid = shmget((key_t)1234, 128, IPC_CREAT | 0600);
13. assert( shmid != -1 );
14.
15. char *s = (char *)shmat(shmid, NULL, 0);
16. assert( s != NULL );
17.
18. printf("shmb s = %s\n", s);
19.
20. shmdt(s);
21. shmctl(shmid, IPC_RMID, NULL);
22. exit(0);
23. }

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值