About Linux IPC (v): System V Shared memory

Source: Internet
Author: User
Tags function prototype semaphore

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 accesses 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:
    1. #include <sys/ipc.h>
    2. #include <sys/shm.h>
    3. int Shmget (key_t key, size_t size, int shmflg);
Key: Function Ftok return value, or ipc_private, when using ipc_private, preferably two process space is shared, such as parent-child process, otherwise the current process generated shared memory identifier (return value), in another process is not easy to obtain;
The Ftok function prototype is: key_t ftok (const char *pathname, int proj_id); The parameter pathname is the file absolute pathname, and proj_id is an integer identifier that 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, which is a parameter that is not 0 when a new piece of shared memory is created. If you are reading a piece of shared memory, the value can be 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, it is necessary to use the function Shmat to connect the slice of shared memory to the current process space, and when a process has finished using shared memory, use the function SHMDT to disconnect and share the memory link.
    1. #include <sys/types.h>
    2. #include <sys/shm.h>
    3. void *shmat (int shmid, const void *shmaddr, int shmflg);
    4. 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, if the parameter is NULL, the system chooses an appropriate address, if SHMADDR is not null and SHMFLG specifies the option shm_rnd, the phase The shared memory should be linked to a Shmlab constant that is rounded down by the address specified by the SHMADDR parameter. If 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: You can specify SHM_RND and shm_rdonly (read-only), and if you specify the SHM_RDONLY option, the calling process has read access to that slice of 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 just disconnects from the slice's shared memory. When a process terminates, the shared memory linked by the process is automatically disconnected.
The Shmat function successfully returned the current process shared memory address, failed to return (void *) -1;SHMDT successfully returned 0, failed to return 1;
Removing shared memory requires the function Shmctl call the Ipc_rmid command to complete.
    1. #include <sys/ipc.h>
    2. #include <sys/shm.h>
    3. int shmctl (int shmid, int cmd, struct shmid_ds *buf);

Shmid: Shared memory area identification;
CMD: Operation command for Shared memory, command Ipc_rmid destroy (destroy) a piece of shared memory, destroy all shmat,shmdt,shmctl to the memory operation will be invalidated, destroy the shared memory to wait until the shared memory reference count becomes 0; ipc_ The SET command sets the SHMID_DS structure member, IPC_STAT returns the current shared memory structure, and the remaining commands view the man manual.
BUF: For pointing to shmid_ds data structure;


Example of system V shared memory:
Server process:
  1. int Sln_shm_get (char *shm_file, void **mem, int mem_len)
  2. {
  3. int shmid;
  4. key_t key;
  5. if (NULL = = fopen (shm_file, "w+")) {
  6. printf ("fopen:%s\n", Strerror (errno));
  7. return-1;
  8. }
  9. Key = Ftok (shm_file, 0);
  10. if (Key < 0) {
  11. printf ("Ftok:%s\n", Strerror (errno));
  12. return-1;
  13. }
  14. Shmid = Shmget (key, Mem_len, ipc_creat);
  15. if (Shmid < 0) {
  16. printf ("Shmget:%s\n", Strerror (errno));
  17. return-1;
  18. }
  19. *mem = (void *) Shmat (shmid, NULL, 0);
  20. if (void *)-1 = = *mem) {
  21. printf ("Shmat:%s\n", Strerror (errno));
  22. return-1;
  23. }
  24. return shmid;
  25. }
  26. int main (int argc, const Char *argv[])
  27. {
  28. char *shm_file = NULL;
  29. char *shm_buf = NULL;
  30. int shmid;
  31. Shmid = Sln_shm_get (Shm_ipc_filename, (void * *) &shm_buf, Shm_ipc_max_len);
  32. if (Shmid < 0) {
  33. return-1;
  34. }
  35. snprintf (Shm_buf, Shm_ipc_max_len, "Hello system V Shaare memory ipc! This was write by server. ");
  36. Sleep (15);
  37. printf ("System V server Delete share memory segment!\n");
  38. //SHMDT (SHM_BUF);
  39. Shmctl (Shmid, Ipc_rmid, NULL); //server after 15 seconds destroy the slice to share memory, at which point the client process will not get the contents of the shared memory
  40. return 0;
  41. }

Client process:

  1. int Sln_shm_get (char *shm_file, void **mem, int mem_len)
  2. {
  3. int shmid;
  4. key_t key;
  5. Key = Ftok (shm_file, 0);
  6. if (Key < 0) {
  7. printf ("Ftok:%s\n", Strerror (errno));
  8. return-1;
  9. }
  10. Shmid = Shmget (key, Mem_len, ipc_creat);
  11. if (Shmid < 0) {
  12. printf ("Shmget:%s\n", Strerror (errno));
  13. return-1;
  14. }
  15. *mem = (void *) Shmat (shmid, NULL, 0);
  16. if (void *)-1 = = *mem) {
  17. printf ("Shmat:%s\n", Strerror (errno));
  18. return-1;
  19. }
  20. return shmid;
  21. }
  22. int main (int argc, const Char *argv[])
  23. {
  24. char *shm_buf = NULL;
  25. int i;
  26. if (Sln_shm_get (Shm_ipc_filename, (void * *) &shm_buf, Shm_ipc_max_len) < 0) {
  27. return-1;
  28. }
  29. printf ("IPC client get:%s\n", shm_buf);
  30. return 0;
  31. }


At run time, the server process is executed first, and the current system shared memory can be viewed using command IPCS:
    1. # IPCS
    2. ------Message Queues--------
    3. Key Msqid owner perms used-bytes messages
    4. ------Shared Memory Segments--------
    5. Key shmid owner perms bytes nattch Status
    6. 0x0010a797 131072 Root 0 4096 1
    7. ------Semaphore Arrays--------
    8. Key Semid owner Perms Nsems

You can see that there is a shared memory area where key is: 0x0010a797, and the shared memory ID is: 131072
    1. #./client
    2. IPC Client Get:hello System V Shaare memory ipc!   This is the write by server.
    3. #

After the server process destroy shared memory, repeat the steps above,
  1. # IPCS
  2. ------Message Queues--------
  3. Key Msqid owner perms used-bytes messages
  4. ------Shared Memory Segments--------
  5. Key shmid owner perms bytes nattch Status
  6. ------Semaphore Arrays--------
  7. Key Semid owner Perms Nsems
  8. The shared memory is no longer present, but the file still exists.
  9. #./client
  10. IPC Client Get:
  11. #


At this point the client cannot get the 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 you can get the maximum amount of shared memory supported by the system.
    1. # Cat/proc/sys/kernel/shmmax
    2. 33554432
    3. #


Can see my current system support maximum shared memory value is: 32M.


The example above can see that System V shared memory is similar to POSIX shared memory, but 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.
Similarly, System V shared memory needs to be synchronized between multiple processes most of the time, and System V can be implemented with its own semaphore, and details will be explained later in the relevant column.
Download the source code in this section:

http://download.csdn.net/detail/gentleliu/8140887
    • Related articles recommended:
    • About Linux IPC (i): socket-based interprocess communication (I.)
    • About Linux IPC (ii): socket-based interprocess communication (bottom)
    • About Linux IPC (iii): MMAP system calls shared memory
    • This article is from: Hobby Technology Network
    • This article link: http://www.ahlinux.com/c/9590.html

About Linux IPC (v): System V 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.