linux进程间通信–共享内存(POSIX 版本)
System V
共享内存模型使用的是key和标识符,这与标准的UNIX I/O模型使用文件名和描述符的做法不一致。这种差异导致System V
共享内存段需要一整套全新的系统调用和命令。由于这些潜在的缺点,因此POSIX
标准又重新定义了共享内存API。
共享内存的使用
:共享内存被映射到进程的虚拟地址空间之后,就可以跟正常的进程空间内存一样进行各种操作了。
其他说明:
- 共享内存并未提供同步机制。所以我们通常需要用其他的机制来同步对共享内存的访问,例如信号量.
- 使用了POSIX共享内存函数,链接时要用到
-lrt
库. - 使用POSIX标准接口shm_open()创建的共享内存对象,可将它认为特殊的文件,可以使用文件操作的相关接口。如修改权限
fchmod()
. - Linux中一般将共享内存创建的文件放在
/dev/shm
目录下。
共享内存的相关接口函数如下:
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/mman.h>
int shm_open(const char *name, int oflag, mode_t mode);
#include <sys/mman.h>
int shm_unlink(const char *name);
除了上面的两个专门的共享内存API.一般也要使用到mmap()
,fstat()
,ftruncate()
以及其他的文件操作函数。下面仅简单的介绍,详细请参考具体章节。
#include <sys/mman.h>
void *mmap(void *addr, size_t len, int prot, int flags,int fildes, off_t off);
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int fstat(int fd, struct stat *statbuf);
#include <unistd.h>
#include <sys/types.h>
int ftruncate(int fd, off_t length);
共享内存创建与删除例程:
#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
int main(void)
{
const char *shm_name = "/sh_mem1";
const int shm_size = 1024;
int shmfd = shm_open(shm_name, O_CREAT | O_RDWR, 0666);
if(shmfd == -1){
printf("shm_open error(%d)\n",errno);
exit(1);
}
if (ftruncate(shmfd, shm_size) == -1){
printf("ftruncate error(%d)\n",errno);
exit(1);
}
struct stat buf;
if(fstat(shmfd,&buf) == -1){
printf("fstat error(%d)\n",errno);
exit(1);
}
printf("shm size:(%ld)\n",buf.st_size);
char *addr = mmap(NULL, shm_size, PROT_READ | PROT_WRITE, MAP_SHARED, shmfd, 0);
strcmp(addr,"hello word");
close(shmfd);
munmap(addr, shm_size);
if (shm_unlink(shm_name) == -1){
printf("shm_unlink error(%d)\n",errno);
exit(1);
}
exit(0);
}
关于技术交流
此处后的文字已经和题目内容无关,可以不看。
qq群:825695030
微信公众号:嵌入式的日常
如果上面的文章对你有用,欢迎打赏、点赞、评论。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)