mmap提供父子进程间的共享内存区的列子:
(1)使用内存映射文件;
(2)使用4.4BSD 匿名内存映射;
(3)使用 /dev/zero 匿名内存映射。
POSIX 提供了两种在无亲缘关系进程间共享内存区的方法:
(1)内存映射文件:由open函数打开,由mmap函数把得到的描述符映射 到当前进程地址空间中的一个文件。
(2)共享内存区对象:由shm_open 打开一个Posix IPC名字,所返回的描述符由mmap函数映射到当前进程的地址空间。
差别在于:获取描述符的手段。Posix 把两者合称为内存区对象。
shm_open、shm_unlink函数
Posix共享内存区涉及两个步骤要求:
(1)指定一个名字参数调用shm_open,以创建一个新的共享内存区对象或打开一个已存在的共享内存区对象。
(2)调用mmap把这个共享内存区映射到调用进程的地址空间。
#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);
// 若成功则为非负描述符,出错-1
int shm_unlink(const char *name);
// 成功0, 出错-1
Link with -lrt.
ftruncate、fstat 函数
处理mmap的时候,普通文件或共享内存区对象的大小都可以通过调用 ftruncate 修改。
#include <unistd.h>
#include <sys/types.h>
int truncate(const char *path, off_t length);
int ftruncate(int fd, off_t length);
// 返回:成功为0, 出错为-1
Posix就该函数对普通文件和共享内存区对象的处理定义有如下不同:
1、普通文件:如果该文件的大小大于length参数,额外的数据就被丢弃掉。如果该文件的大小小于length,那么该文件是否修改以及其大小是否增长是未加说明的。
2、共享内存区对象:ftruncate把该对象的大小设置成length字节。
我们调用ftruncate来指定新创建的共享内存区对象的大小,或者修改已存在的对象的大小。当打开一个已存在的共享内存区对象时,可调用fstat来获取有关该对象的信息。
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int stat(const char *pathname, struct stat *buf);
int fstat(int fd, struct stat *buf);
// 成功为0,出错-1
int lstat(const char *pathname, struct stat *buf);
#include <fcntl.h> /* Definition of AT_* constants */
#include <sys/stat.h>
int fstatat(int dirfd, const char *pathname, struct stat *buf, int flags);
stat 结构:
struct stat {
dev_t st_dev; /* ID of device containing file */
ino_t st_ino; /* inode number */
mode_t st_mode; /* file type and mode */
nlink_t st_nlink; /* number of hard links */
uid_t st_uid; /* user ID of owner */
gid_t st_gid; /* group ID of owner */
dev_t st_rdev; /* device ID (if special file) */
off_t st_size; /* total size, in bytes */
blksize_t st_blksize; /* blocksize for filesystem I/O */
blkcnt_t st_blocks; /* number of 512B blocks allocated */
/* Since Linux 2.6, the kernel supports nanosecond
precision for the following timestamp fields.
For the details before Linux 2.6, see NOTES. */
struct timespec st_atim; /* time of last access */
struct timespec st_mtim; /* time of last modification */
struct timespec st_ctim; /* time of last status change */
#define st_atime st_atim.tv_sec /* Backward compatibility */
#define st_mtime st_mtim.tv_sec
#define st_ctime st_ctim.tv_sec
};
当 fd 代指一个共享内存区对象时,只有四个成员含有信息。st_mode、st_uid、st_gid、st_size。