使用Posix共享内存区实现进程间通信
使用Posix共享内存区通常涉以下步骤:
- 进程A 调用shm_open 创建共享内存区
- 进程A调用ftruncate修改共享内存区大小
- 进程A 调用mmap将共享内存区映射到进程地址空间ptrA
- 进程A 使用ptrA对共享内存区进程更改
- 进程B 使用shm_open打开已有共享内存区
- 进程B 调用fstat获取共享内存区大小
- 进程B 调用mmap将共享内存区映射到进程地址空间ptrB
- 进程B 使用ptrB对共享内存区进行更改
- 最后由进程A/B调用shm_unlink删除共享内存区
1、shm_open 创建/打开共享内存区
shm_open调用成功后返回共享内存区的文件描述符, 并在/dev/shm目录下生成相应的文件。
shm_open函数声明包含在文件 sys/mman.h 中;
#include <sys/mman.h>
#include <sys/stat.h> /* For mode constants */
#include <fcntl.h> /* For O_* constants */
int shm_open(const char *name, int oflag, mode_t mode);
oflag的值包含在文件 fcntl.h中
#define O_RDONLY 00 //只读
#define O_WRONLY 01 //只写
#define O_RDWR 02 //可读可写
#define O_CREAT 0100 //创建
#define O_EXCL 0200 //如果共享内存区已存在则返错误
mode的值包含在文件sys/stat.h中
#define S_IRUSR __S_IREAD /* Read by owner. */
#define S_IWUSR __S_IWRITE /* Write by owner. */
#define S_IXUSR __S_IEXEC /* Execute by owner. */
#define S_IRGRP (S_IRUSR >> 3) /* Read by group. */
#define S_IWGRP (S_IWUSR >> 3) /* Write by group. */
#define S_IXGRP (S_IXUSR >> 3) /* Execute by group. */
#define S_IROTH (S_IRGRP >> 3) /* Read by others. */
#define S_IWOTH (S_IWGRP >> 3) /* Write by others. */
#define S_IXOTH (S_IXGRP >> 3) /* Execute by others. */
2、ftruncate修改内存区大小
ftruncate包含在头文件unistd.h中
/* Truncate the file FD is open on to LENGTH bytes. */
int ftruncate (int __fd, __off_t __length)
fd:shm_ope返回的描述符
length:共享内存区的大小
3、fstat获取文件大小
fstat包含在头文件sys/stat.h中
在打开已存在的共享内存区时,可以用fstat获取共享内存区的大小。
/* Get file attributes for the file, device, pipe, or socket
that file descriptor FD is open on and put them in BUF. */
int fstat (int __fd, struct stat *__buf)
fd:shm_open返回的描述符
stat.st_size是共享内存区的大小
4、mmap将共享内存区映射到进程地址空间
mmap包含在头文件mman.h中
void *mmap (void *__addr, size_t __len, int __prot,
int __flags, int __fd, __off_t __offset)</