Linux IPC Practice (TEN)--posix shared memory

Source: Internet
Author: User
Tags lstat posix

1. Create/acquire a shared memory

#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);

Parameters:

Name: Shared memory names;

Oflag: With the Open function type, can be o_rdonly, o_wronly, O_RDWR, can also be bitwise OR on o_creat, O_EXCL, O_trunc.

mode: This parameter always needs to be set, if Oflag does not specify O_creat, mode can be set to 0;

return value:

Success: Returns a file descriptor;

Failure: return-1;

Note-posix IPC Name limitations:

1. Must start with "/", and can not be followed by "/", shape such as:/file-name;

2. Name length cannot exceed Name_max

3. When linking: 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 modify it to a size of 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 Shared Memory status

int fstat (int fd, struct stat *buf);

This function can not only be used to get the shared memory state, but also can be used to get the file state, with the stat, Lstat type, as previously described;


/** Example: Get the shared memory mode and size **/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 getting permissions, you need to & 0777, and you want to print printf in%o, octal mode    ("mode:%o\n", buf.st_mode&0777);    printf ("Size:%ld\n", buf.st_size);    Close (Shmid);}

4. Delete a shared memory object

int Shm_unlink (const char *name);
Example: int main (int argc,char *argv[]) {    shm_unlink ("/xyz");}

5. Mapping/offloading of shared memory

#include <sys/mman.h>void *mmap (void *addr, size_t length, int prot, int flags, int fd, off_t offset); int Munmap (voi D *addr, size_t length);

Parameters:

Addr: The starting address to be mapped, usually specified as NULL, allowing the kernel to be automatically selected;

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

Prot: Map Area protection method (see below);

Flags: flags (usually specified as map_shared for interprocess communication);

FD: File descriptor (filled with the shared memory ID returned by Shm_open);

offset: Offsets from the beginning of the file header (typically filled with 0);

Prot

Description

Prot_read

Page readable

Prot_write

Pages can be written

Proc_exec

Page executable

Proc_none

Page not accessible

Flags

Description

Map_shared

The change is shared

Map_private

The change is private.

Map_fixed

Explain the addr parameter exactly, and if you do not specify this parameter, it will be aligned with memory of 4 K size

Map_anonymous

Create an anonymous map area that does not involve files

Mmap return Value:

Success: Returns the starting address of the memory area mapped to;

failure: return map_failed;

Note: Mmap failed to return the cause of the eacces error:

eacces A file descriptor refers to A non-regular file.

Or Map_private was requested, and FD is not open for reading.

Or map_shared was requested and Prot_write are set, but FD are not open

In Read/write (o_rdwr) mode. Or prot_write is set, and the file is append-only.

/** read data from 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);}

Attached

-posix shared memory is created by default in the/DEV/SHM directory

-You can use the OD command to view the contents of shared memory

Od-c/dev/shm/xyz

Linux IPC Practice (TEN)--posix shared memory

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.