shm_openBrief introduction of function
shm_open:To create a memory file, the path requires something like / filename, starting with / and then the filename, with no /.
shm_openThe prototype and header files of the function are as follows:
1 NAME 2 shm_open, shm_unlink - create/open or unlink POSIX shared memory objects 3 4 SYNOPSIS 5 #include <sys/mman.h> 6 #include <sys/stat.h> /* For mode constants */ 7 #include <fcntl.h> /* For O_* constants */ 8 9 int shm_open(const char *name, int oflag, mode_t mode); 10 11 int shm_unlink(const char *name); 12 //Delete open file descriptor 13 14 Link with -lrt. 15 //Note that when you compile, you should add the link library, for example: 16 gcc a.out -o a -lrt 17 RETURN VALUE 18 On success, shm_open() returns a nonnegative file descriptor. On failure, shm_open() returns -1. 19 shm_unlink() returns 0 on success, or -1 on error.
【Example]
Writing files to shared memory:
Compile:
gcc shm_open_w.c -o shm_open_w -lrt
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<unistd.h> #include<fcntl.h> #include<sys/types.h> #include<sys/stat.h> #include<sys/mman.h> /*Package print error function*/ void sys_err(const char *str,int num){ perror(str); exit(num); } int main(int argc,char *argv[]) { int fd = shm_open("/hello.txt",O_RDWR|O_CREAT|O_EXCL,0777); /*O_EXCL|O_CREAT,If the document already exists, it is reported that it is wrong.*/ if(fd < 0){ fd = shm_open("/hello.txt",O_RDWR,0777); /*Open file to read and write directly*/ }else ftruncate(fd,4096); /*If you create files for yourself, allocate memory space for files.*/ void *ptr = mmap(NULL,4096,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0); puts("start writeing data...."); /*Here is the file for writing.*/ strcpy((char*)ptr,"i am lixiaogang"); puts("write over"); getchar(); shm_unlink("/hello.txt"); close(fd); return 0; }
Read files to shared memory
Compile:
gcc shm_open_r.c -o shm_open_r -lrt
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<unistd.h> #include<fcntl.h> #include<sys/types.h> #include<sys/stat.h> #include<sys/mman.h> void sys_err(const char *str,int num){ perror(str); exit(num); } int main(int argc,char *argv[]) { int fd = shm_open("/hello.txt",O_RDWR|O_CREAT|O_EXCL,0777); if(fd < 0){ fd = shm_open("/hello.txt",O_RDWR,0777); }else ftruncate(fd,4096); void *ptr = mmap(NULL,4096,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0); puts("start reading data...."); puts((char*)ptr); puts("read over"); shm_unlink("/hello.txt"); close(fd); return 0; }