Shared memory and memory mapping for Linux

Source: Internet
Author: User

A. POSIX shared memory implementation

Shared memory is a piece of memory shared between processes. Is the fastest kind of IPC communication organization. The POSIX shared memory mechanism is mainly implemented through the memory Mapping (MMAP) mechanism.

Shared memory between processes uses the following fixed steps:

1. Create a shared memory

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

Name is the shared memory name, and each process finds the same memory by name.

Oflag, is this memory attribute. Similar to file properties. With O_rdwr/o_rdonly/o_creat, the first time you create shared memory you must have a o_creat flag bit.

Mode, is the permission code.

When it opens successfully, it will create a virtual file/DEV/SHM/SHM. XXXX, where xxxx is name

Example: int fd = Shm_open ("Test", o_rdwr,666);

The/dev/shm/shm.test file will be created.

After the Shm_open succeeds, a file descriptor FD is returned. You can understand that you are allocating a space in the kernel and assigning an FD number to the application.

Note here that if a process has created a shared memory, the other processes on the other side will open the shared memory using only

Shm_open (name,flag,0); And

2. Set the memory size.

int ftruncate (int fd, off_t length);

Ftruncate operation of the FD can be a file open after the FD, but also shm_open open FD.

The normal file will be forced by ftruncate to length (not enough to add 0 space, more than is truncated

If shared memory, it will indicate that the shared memory is set to length size.

If setting Ftruncate returns 0

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.