Description of the Linux IPC (children under five): System V Shared memory

Source: Internet
Author: User
Tags function prototype posix semaphore

Copyright Notice: respect for the original. Reprint please keep Source: blog.csdn.net/shallnet either .../gentleliu, article learning Communication, not for commercial use "
System V shared memory is similar to POSIX shared memory, and System V shared memory is called the Shmget function and the Shamat function.
The Shmget function creates a shared memory area, or an access to an existing memory area, similar to the system calling the open and POSIX shared memory shm_open functions of shared memory.

The Shmget function prototype is:

       #include <sys/ipc.h>       #include <sys/shm.h>       int shmget (key_t key, size_t size, int shmflg);
Key: Function Ftok return value. Or ipc_private, when using Ipc_private. The best two process spaces are shared, such as the parent-child process, or the shared memory ID (return value) produced by the current process. It is not easy to get inside a process.
The Ftok function prototype is: key_t ftok (const char *pathname, int proj_id); The parameter pathname is the absolute pathname of the file, and proj_id is an integer identifier. The function converts an existing pathname and an integer identifier into a key_t value (the return value), called the IPC key.
Size: Creates a new shared memory size when a new piece of shared memory is created. The value is a parameter that is not 0. Assume that you are reading a piece of shared memory, which can be a value of 0.


SHMFLG: Combination of Read and write permission values.

Ipc_creat (Create new shared memory) or ipc_creat| IPC_EXCL (when the shared memory that will be created already exists, the attempt to create will return eexist).

In fact, the combination of ipc_creat and IPC_EXCL is similar to the o_creat and o_excl combinations of the open function.


The function returns the identity of the shared memory area.

The SHMXXX function operation shared memory will use this function to return a value.

This function is similar to the POSIX shared memory Shm_open function function.


When Shmget creates or opens a shared memory area. You need to use the function Shmat to connect the slice of shared memory to the current process space, and use the function SHMDT to disconnect and share the memory link after a process has used the shared memory.


       #include <sys/types.h>       #include <sys/shm.h>       void *shmat (int shmid, const void *shmaddr, int shmflg) ;       int SHMDT (const void *SHMADDR);  
Shmid: Is the shared memory identifier returned by the function Shmget function.
SHMADDR: Connect to the address of the calling process address space, assuming that the parameter is NULL, the system chooses an appropriate address. Assuming that shmaddr is not empty and SHMFLG specifies the option shm_rnd, the corresponding shared memory is linked to a Shmlab constant that is rounded down by the address specified by the SHMADDR parameter. Assuming that shmaddr is not empty and SHMFLG does not specify SHM_RND, the shared memory address is linked to the address specified by the SHMADDR parameter.
SHMFLG: Ability to specify SHM_RND and Shm_rdonly (read only), assuming the shm_rdonly option is specified. The calling process only has read access to the slice's shared memory, otherwise the process will have read and write access to that slice of memory.


The function shmdt does not delete the specified shared memory, it is simply a link to disconnect the shared memory from the slice. When a process terminates. The shared memory that the process links to will voluntarily disconnect itself.
The Shmat function successfully returned the current process shared memory address, and the failed return (void *) -1;SHMDT successfully returned 0. Failed to return-1;
Deleting shared memory requires the function Shmctl call Ipc_rmid command to complete.
       #include <sys/ipc.h>       #include <sys/shm.h>       int shmctl (int shmid, int cmd, struct shmid_ds *buf);

Shmid: Shared memory area identity.
CMD: Operation command for Shared memory, command Ipc_rmid destroy (destroy) a piece of shared memory, destroy all Shmat. Shmdt,shmctl the memory operation of the slice will be invalidated. The shared memory is destroyed until the shared memory reference count changes to 0. The Ipc_set command sets the SHMID_DS structure member; Ipc_stat returns the current shared memory structure. The remaining commands view the man manual.
BUF: For pointing to shmid_ds data structure;


Sample system V Shared memory Demo:
Server process:
int Sln_shm_get (char *shm_file, void **mem, int mem_len) {int shmid;    key_t key;        if (NULL = = fopen (shm_file, "w+")) {printf ("fopen:%s\n", Strerror (errno));    return-1;    } key = Ftok (shm_file, 0);        if (Key < 0) {printf ("Ftok:%s\n", Strerror (errno));    return-1;    } Shmid = Shmget (key, Mem_len, ipc_creat);        if (Shmid < 0) {printf ("Shmget:%s\n", Strerror (errno));    return-1;    } *mem = (void *) Shmat (shmid, NULL, 0);        if (void *)-1 = = *mem) {printf ("Shmat:%s\n", Strerror (errno));    return-1; } return shmid;}    int main (int argc, const char *argv[]) {char *shm_file = NULL;    char *shm_buf = NULL;    int shmid;    Shmid = Sln_shm_get (Shm_ipc_filename, (void * *) &shm_buf, Shm_ipc_max_len);    if (Shmid < 0) {return-1; } snprintf (Shm_buf, Shm_ipc_max_len, "Hello system V Shaare memory ipc!    This was write by server. ");      Sleep (15); printf ("System V server Delete Share mEmory segment!\n ");    SHMDT (SHM_BUF); Shmctl (Shmid, Ipc_rmid, NULL); The server destroy the slice to share memory after 15 seconds. The client process will not get the contents of the shared memory at this time return 0;}

Client process:

int Sln_shm_get (char *shm_file, void **mem, int mem_len) {    int shmid;    key_t key;    Key = Ftok (shm_file, 0);    if (Key < 0) {        printf ("Ftok:%s\n", Strerror (errno));        return-1;    }    Shmid = Shmget (key, Mem_len, ipc_creat);    if (Shmid < 0) {        printf ("Shmget:%s\n", Strerror (errno));        return-1;    }    *mem = (void *) Shmat (shmid, NULL, 0);    if (void *)-1 = = *mem) {        printf ("Shmat:%s\n", Strerror (errno));        return-1;    }    return shmid;} int main (int argc, const char *argv[]) {    char *shm_buf = NULL;    int i;    if (Sln_shm_get (Shm_ipc_filename, (void * *) &shm_buf, Shm_ipc_max_len) < 0) {        return-1;    }    printf ("IPC Client get:%s\n", shm_buf);    return 0;}


Execute the server process first, using the command IPCS to view the current system shared memory:

Can see that there is a shared memory area, where key is: 0x0010a797, the shared memory ID is: 131072
#./client IPC Client Get:hello system V Shaare memory ipc! This is the write by server. #

After the server process destroy shared memory, repeat the above steps,
# IPCS------Message Queues--------Key msqid owner perms used-bytes messages------Shared Memory Segments--------key Shmid owner perms bytes nattch status------Semaphore Arrays--------Key semid owner perms Nsems  at this time the shared memory is gone, but the file still exists In.



At this point the client is unable to acquire previously shared memory content.
In addition, the IPCRM command can delete the specified shared memory area on the command line.
By reading the file/proc/sys/kernel/shmmax can get the maximum value of shared memory supported by the system.
# cat/proc/sys/kernel/shmmax33554432#


Can see me now the system supports the maximum shared memory value is: 32M.


The demo sample shows that the System V shared memory is similar to POSIX shared memory, except that the size of the POSIX shared memory can be changed at any time by Ftruncate, while the shared memory size of System V is determined at shmget.


The same, System V shared memory most of the time also needs to be synchronized between multiple processes, System V can use its own semaphore to achieve, the details will be synchronized in the relevant column specific explanation.
This section source code download:

http://download.csdn.net/detail/gentleliu/8140887

Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.

Description of the Linux IPC (children under five): System V Shared memory

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.