Linux inter-process communication (IPC) programming practices (8) use of shared memory-POSIX shared memory (API)

Source: Internet
Author: User
Tags lstat

Linux inter-process communication (IPC) programming practices (8) use of shared memory-POSIX shared memory (API)

1. Posix provides two methods to share memory areas between unrelated processes:

(1) memory ing file: open the function first, and then call the mmap function to map the obtained descriptor to a file in the current process address space (this is used in the previous blog ).

(2) shared memory area object: First open a Posix IPC name (or a path name in the file system) with shm_open, and then call mmap to map the returned descriptor to the address space of the current process. Both methods need to call mmap. The difference is that it is used to obtain the descriptor as one of the mmap parameters.

2. Posix shared memory area object

The Posix shared memory zone requires the following two steps:

(1) specify a name parameter to call shm_open to create a new shared memory area object or open an existing shared memory area object.

(2) Call mmap to map the shared memory area to the address space of the calling process.

Note: mmap is used to map a memory area object to the address space of the calling process. It is an opened descriptor of the object.

The Posix shared memory area object API is as follows:

 

#include 
 
  #include 
  
          /* For mode constants */#include 
   
                 /* For O_* constants */int shm_open(const char *name, int oflag, mode_t mode);int shm_unlink(const char *name);        int ftruncate(int fd, off_t length);int fstat(int fd, struct stat *buf);
   
  
 

1. Create/obtain a shared memory

 

 

int shm_open(const char *name, int oflag, mode_t mode);

 

Parameters:

Name: name of the shared memory;

Oflag: function type. It can be O_RDONLY, O_WRONLY, O_RDWR, O_CREAT, O_EXCL, and O_TRUNC.

Mode: this parameter always needs to be set. If oflag does not specify O_CREAT, the mode can be set to 0;

Return Value:

Success: A file descriptor is returned;

Failed:-1 is returned;

Note-Posix IPC name restrictions:

1. It must start with "/" and cannot be followed by "/", for example:/file-name;

2. The name length cannot exceed NAME_MAX.

3. Link with-lrt.

/** Example: Open and Close shared memory **/int main (int argc, char * argv []) {int shmid = shm_open ("/xyz ", o_RDWR | O_CREAT, 0666); if (shmid =-1) err_exit ("shmget error"); cout <"share memory open success" <endl; close (shmid );}
2. Modify the shared memory size

 

int ftruncate(int fd, off_t length); 
This function can be used not only to modify the shared memory size, but also to modify the file size.
/** Example: Modify the shared memory size to the size of a Student struct **/struct Student {char name [32]; int age ;}; int main (int argc, char * argv []) {int shmid = shm_open ("/xyz", O_RDWR | O_CREAT, 0666); if (shmid =-1) err_exit ("shmget error"); if (ftruncate (shmid, sizeof (Student) =-1) err_exit ("ftruncate error "); cout <"share memory change size success" <endl; close (shmid );}
3. Get the shared memory status
int fstat(int fd, struct stat *buf);  
This function can be used not only to obtain the shared memory status, but also to obtain the File status, which is similar to the stat and lstat types described earlier;
// Stat struct stat {dev_t st_dev;/* ID of device ining file */ino_t st_ino;/* inode number */mode_t st_mode;/* protection */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 */time_t st_atime;/* time of last access */time_t st_mtime;/* time of last modification */time_t st_ctime; /* time of last status change */};
/** Example: Get the mode and size of the shared memory **/int main (int argc, char * argv []) {int shmid = shm_open ("/xyz ", o_RDWR | O_CREAT, 0666); if (shmid =-1) err_exit ("shmget error"); if (ftruncate (shmid, sizeof (Student) =-1) err_exit ("ftruncate error"); struct stat buf; if (fstat (shmid, & buf) =-1) err_exit ("lstat error"); // note: when obtaining the permission, & on 0777 is required, and printf ("mode: % o \ n", buf must be printed in % o and mode. st_model & 0777); printf ("size: % ld \ n", buf. st_size); close (shmid );}
4. Delete A Shared Memory Object
int main(int argc,char *argv[])  {      shm_unlink("/xyz");  }  
5. Shared Memory ing/uninstallation
#include 
 
    void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset);  int munmap(void *addr, size_t length);  
 

 

Parameters:

Addr: the starting address to be mapped. It is usually specified as NULL to allow the kernel to automatically select;

Length: the number of bytes mapped to the process address space, usually the size of the previously created shared memory;

Prot: ing protection method (see below );

Flags: flag (usually set to MAP_SHARED for inter-process communication );

Fd: file descriptor (fill in the shared memory ID returned by shm_open );

Offset: the offset starting from the file header (usually 0 );

 

Prot

Description

PROT_READ

Page readable

PROT_WRITE

Page writable

PROC_EXEC

Page executable

PROC_NONE

Page inaccessible

 

Flags

Description

MAP_SHARED

Changes are shared.

MAP_PRIVATE

Changes are private

MAP_FIXED

The addr parameter is interpreted accurately. If this parameter is not specified, alignment is performed with 4 K memory size.

MAP_ANONYMOUS

Create an anonymous ing area that does not involve files

 

Mmap return value:

Success: return the starting address of the mapped memory area;

Failed: MAP_FAILED is returned;

Note: The cause of EACCES error returned when mmap fails:

Eacces a file descriptor refers to a non-regular file.

Or MAP_PRIVATE was requested, but fd is not open for reading.

Or MAP_SHARED was requested and PROT_WRITE is set, but fd is not open

In read/write (O_RDWR) mode. Or PROT_WRITE is set, but the file is append-only.

/** Example: write data to the shared memory **/int main (int argc, char * argv []) {int shmid = shm_open ("/xyz", O_RDWR, 0); if (shmid =-1) err_exit ("shm_open error"); struct stat buf; if (fstat (shmid, & buf) =-1) err_exit ("fstat error"); Student * p = (Student *) mmap (NULL, buf. st_size, PROT_WRITE, MAP_SHARED, shmid, 0); if (p = MAP_FAILED) err_exit ("mmap error"); strcpy (p-> name, "Hadoop "); p-> age = 5; munmap (p, buf. st_size); close (shmid );}

 

/** Read data from the shared memory **/int main (int argc, char * argv []) {int shmid = shm_open ("/xyz", O_RDONLY, 0 ); if (shmid =-1) err_exit ("shm_open error"); struct stat buf; if (fstat (shmid, & buf) =-1) err_exit ("fstat error"); Student * p = (Student *) mmap (NULL, buf. st_size, PROT_READ, MAP_SHARED, shmid, 0); if (p = MAP_FAILED) err_exit ("mmap error"); cout <"name: "<p-> name <", age: "<p-> age <endl; munmap (p, buf. st_size); close (shmid );}

[Note]

-Posix shared memory is created in the/dev/shm directory by default.

-You can use the od command to view the shared memory content.

Od-c/dev/shm/xyz







 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.