Inter-process communication---shared memory

Source: Internet
Author: User
Tags semaphore

I. Introduction to the IPC (inter-process communication, interprocess communication) object The IPC objects for System V have shared memory, message queues, and semaphores.



Note: In the IPC communication mode, each IPC object has a unique name, called "Key", whether it is using Message Queuing or shared memory, or even a semaphore . With the key, the process is able to identify the object being used. The relationship between the "key" and the IPC object is like a file name in a file, through a filename, a process can read and write data within a file, and even multiple processes can share a single file. In the IPC communication mode, the use of "keys" also enables an IPC object to be shared by multiple processes. Introduction to Shared memory <1> shared memory is one of the most efficient ways to communicate between processes, and processes can read and write directly to memory without requiring any copy of the data. <2>In order to exchange information between multiple processes, the kernel specifically leaves out a chunk of memory that can be mapped to its own private address space by the process that needs to be accessed. The process can read and write directly to this piece of memory without having to copy the data, thereby greatly improving efficiency. <3> because multiple processes share a piece of memory, you also need to rely on some kind of synchronization mechanism. Three, the characteristics of shared memory


Iv. operation flow of shared memory <1> Create/Open Shared memory <2> map shared memory, that is, map the specified shared memory to the address space of the process for access <3> revoke shared memory mappings <4> Delete shared memory Objects v. Related APIs A. Getting A piece of shared memory


Function: Allocate a piece of shared memory return value: The call successfully returns a shmid (like opening one or creating a file with a file descriptor); call failed return-1. Parameter description: <1>key identifies the key value of shared memory (as if the file's identity is a filename): 0/ipc_private. When the value of key is Ipc_private, the function shmget () Creates a new shared memory, and if the value of key is 0, and the ipc_create is set in the parameter SHMFLG, a new shared memory is created as well. shared memory, which is allocated in this way, is typically used for inter-process communication between relatives. Note: We generally get the key value by Ftok this function

Function: Gets the key value parameter description of an IPC object: Pthname is the path to the file name you specify (it must be present and accessible), generally we write a directory proj_id: together with Pthname to complete the parameters that create the key value, although it is an int, But only 8 bits are used. Generally we write a character instead. Example: Case:


Results of the operation:



<2> the size is the length of the shared memory to be established. All memory allocation operations are in page units. So if a process only requests a single byte of memory, the memory will also be allocated a full page (the default size of a page in the i386 machine Pace_size = 4096 bytes). &LT;3&GT;SHMFLG valid flags include Ipc_creat and IPC_EXCL, and their function is equivalent to open () O_creat and O_EXCL. Ipc_creat if the shared memory does not exist, create a shared memory, or open the existing IPC_EXCL directly if the shared memory does not exist, the new shared memory is established, or an error occurs



Example one: If the key value is key, create a shared memory size of 4k, the access permission is 066, if it already exists then return its identification number int shmid;if (Shmid = Shmget (key,4 * 1024,0666 |    ipc_creat)) < 0) {perror ("Fail to Shmget"); Exit (Exit_failure)} example two, the assumption that the key value is key, create a shared memory size of 1k, access to 0666, if already exists the error int shmid;if ((Shmid = Shmget (key,1024,0666 | Ipc_creat |    IPC_EXCL)) < 0) {perror ("Fail to Shmget"); Exit (exit_failure);} B. Mapping of Shared memory



The function Shmat maps the identification number to Shmid shared memory into the address space of the calling process. Parameter description: Shmid: Shared memory zone identifier to be mapped SHMADDR: Maps shared memory to the specified address (if NULL, indicates system auto-complete mapping) shmflg:shm_rdonly shared memory read-only default 0: Shared memory is readable and writable. Return value: The call successfully put back the mapped address, error put back (void *)-1; C. Cancel the mapping between shared memory and user processes



The parameter shmaddr is the address where the Shmat mapping was successfully put back. Note: When a process no longer needs a shared memory segment, it calls the SHMDT () system call to cancel the segment, but this does not really remove the segment from the kernel, instead, the value of the Shm_nattch domain of the associated SHMID_DS structure is reduced by 1when this value is 0 o'clock, the kernel removes the shared segment physically.。 D. Controlling shared memory



Parameter description: Shmid shared memory ID cmd Ipc_stat get the state of shared memory Ipc_set change the state of shared memory ipc_rmid Deleting shared memoryBUF is a struct-body pointer. When Ipc_stat, the acquired state is placed in the structure. If you want to change the state of shared memory, specify it with this struct;


Attention:1. The ipc_rmid command does not actually delete a segment from the kernel, but simply marks the segment as deleted, and the actual deletion occurs when the last process leaves the shared segment . 2. When CMD is Ipc_rmid, the third argument should be null. Well, most of us are doing this, using this function to delete shared memory. Case study:


Click (here) to collapse or open

  1. #include <sys/shm.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <semaphore.h>
  6. #include <fcntl.h>
  7. #include <sys/stat.h>
  8. #define BUFF_SIZE 1024
  9. int father_do_work (int shmid)
  10. {
  11. Char *buf;
  12. void *shmaddr;
  13. Sem_t *prsem;
  14. Sem_t *pwsem;
  15. Well-known signal volume
  16. if (Prsem = Sem_open ("Rsem", o_creat,0666,0) = = = sem_failed)
  17. {
  18. Perror ("Fail to SEM open");
  19. return-1;
  20. }
  21. Well-known signal volume
  22. if (Pwsem = Sem_open ("Wsem", o_creat,0666,1) = = = sem_failed)
  23. {
  24. Perror ("Fail to SEM open");
  25. return-1;
  26. }
  27. Mapping shared memory
  28. if ((shmaddr = Shmat (shmid,null,0)) = = (void *)-1)
  29. {
  30. Perror ("Fail to Shmat");
  31. Exit (Exit_failure);
  32. }
  33. BUF = (char *) shmaddr;
  34. while (1)
  35. {
  36. if (sem_wait (Pwsem) < 0)
  37. {
  38. Perror ("Fail to Sem wait");
  39. Break
  40. }
  41. printf (">");
  42. Fgets (Buf,buff_size,stdin);
  43. Buf[strlen (BUF)-1] = ' + ';
  44. if (Sem_post (Prsem) < 0)
  45. {
  46. Perror ("Fail to Sem post");
  47. Break
  48. }
  49. if (strncmp (buf, "Quit", 4) = = 0)
  50. {
  51. if (SHMDT (SHMADDR) < 0)
  52. {
  53. Perror ("Fail to Shmaddr");
  54. Exit (Exit_failure);
  55. }
  56. Break
  57. }
  58. Usleep (500);
  59. }
  60. return 0;
  61. }
  62. int child_do_work (int shmid)
  63. {
  64. Char *buf;
  65. void *shmaddr;
  66. Sem_t *prsem;
  67. Sem_t *pwsem;
  68. //
  69. if (Prsem = Sem_open ("Rsem", o_creat,0666,0) = = = sem_failed)
  70. {
  71. Perror ("Fail to SEM open");
  72. return-1;
  73. }
  74. if (Pwsem = Sem_open ("Wsem", o_creat,0666,1) = = = sem_failed)
  75. {
  76. Perror ("Fail to SEM open");
  77. return-1;
  78. }
  79. Mapping shared memory
  80. if ((shmaddr = Shmat (shmid,null,0)) = = (void *)-1)
  81. {
  82. Perror ("Fail to Shmat");
  83. Exit (Exit_failure);
  84. }
  85. BUF = (char *) shmaddr;
  86. while (1)
  87. {
  88. if (sem_wait (Prsem) < 0)
  89. {
  90. Perror ("Fail to Prsem");
  91. Break
  92. }
  93. printf ("Read buf:%s.\n", buf);
  94. if (Sem_post (Pwsem) < 0)
  95. {
  96. Perror ("Fail to Pwsem");
  97. Break
  98. }
  99. if (strncmp (buf, "Quit", 4) = = 0)
  100. {
  101. if (SHMDT (SHMADDR) < 0)
  102. {
  103. Perror ("Fail to Shmaddr");
  104. Exit (Exit_failure);
  105. }
  106. Break
  107. }
  108. }
  109. return 0;
  110. }
  111. int main ()
  112. {
  113. int shmid;
  114. int pid;
  115. void *shmaddr;
  116. Create shared memory
  117. if (Shmid = Shmget (ipc_private,buff_size,0666 | ipc_creat)) < 0)
  118. {
  119. Perror ("Fail to Shmget");
  120. Exit (Exit_failure);
  121. }
  122. if ((PID = fork ()) < 0)
  123. {
  124. Perror ("Fail to Fork");
  125. Exit (Exit_failure);
  126. }else if (pid = = 0) {
  127. Child_do_work (Shmid);
  128. }else{
  129. Father_do_work (Shmid);
  130. Wait (NULL);
  131. if (Shmctl (Shmid,ipc_rmid,null) < 0)
  132. {
  133. Perror ("Fail to Shmctl");
  134. Exit (Exit_failure);
  135. }
  136. }
  137. Exit (exit_success);
  138. }

Operation Result:





Inter-process communication---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.