System v Shared memory and code examples for inter-process communication between Linux

Source: Internet
Author: User
Tags readable stdin

Shared memory is the fastest and most efficient form of interprocess communication, and when shared memory is mapped to the address space of a process that shares it, the data transfer between processes is no longer involved in the kernel, and the process can read the kernel directly without having to copy the data through the kernel system calls. In general usage, there is a need for synchronization between processes that write or read data from shared memory, such as through semaphores and mutexes.

Shared memory has System V shared memory and POSIX shared memory, this article describes System V shared memory.
System v Shared Memory header file and related function prototypes:
#include <sys/shm.h>

int Shmget (key_t key, size_t size, int oflag);
Function: Create a new shared memory area, or access a shared memory area that already exists.
Return value: If the identifier for the shared memory area is returned successfully, return 1 if there is an error
Parameters: Key is a value, can be generated with Ftok, can also be used ipc_private; Size is the size of the memory area specified in bytes, when a new shared memory area is created, a size value of not 0 is specified, and the size byte is initialized to 0, and when an existing shared memory area is used, the size value needs to be 0; Oflag is read-write and can also be used with ipc_creat or ipc_creat| IPC_EXCL bitwise OR.


void *shmat (int shmid, const void *shmaddr, int flag);
Function: Maps the shared memory area created by Shmget to the address space of the calling process.
Return value: Returns 1 if an error occurs if the start address of the mapping area is returned successfully.
Parameters: Shmid is the identifier returned by Shmget, SHMADDR is the specified address pointer, if it is a null pointer, the system will automatically assign the address, which is the best use of portability, is the recommended usage, if SHMADDR is a non-null pointer, The mapped area address returned depends on whether the third parameter flag specifies SHM_RND, if no shm_rnd is specified, the map address is attached to the address specified by the SHMADDR parameter, and if SHM_RND is specified, The map address is attached to the address specified by the SHMADDR parameter down a Shmlba constant; flag defaults to 0 for read-write, and if shm_rdonly represents read-only access.

int SHMDT (const void *SHMADDR);
Function: Close this shared memory area mapping, when the process terminates, the shared memory map is automatically closed, but not deleted, can be removed by the SHMCTL function of the Ipc_rmid command.
Return value: Successfully returned 0, error returned-1

int shmctl (int shmid, int cmd, struct shmid_ds *buf);
Function: Operation Shared memory Area
Return value: Successfully returned 0, error returned-1.
Parameters: The cmd parameter has three commands, Ipc_rmid removes the shmid labeled Shared memory area from the system, Ipc_set sets the three members of the SHMID_DS structure to the specified shared memory area Shm_perm.uid,shm_perm.gid and Shm_ Perm.mode, the values of these three members are derived from the corresponding members in the structure that the BUF parameter points to, Ipc_stat is the SHMID_DS structure taken from the shared memory area and saved in the parameter BUF structure.

The general programming steps are as follows:
1. Create Shared Memory:
Create shared memory through function shmget ()
2. Mapping Shared Memory:
Mapping shared memory created to a process through the function shmget ()
3. Use shared Memory:
4. Undo Shared Memory Mappings
function Shmdt ()
5. Delete the shared memory map:
function Shmctl ()

code example SHM_TEST.C: The parent process reads data from the terminal into the shared memory, and the child process reads the data from the shared memory to display to the terminal

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <sys/types.h>
  5. #include <sys/ipc.h>
  6. #include <sys/shm.h>
  7. #define BUFFER_SIZE 1024
  8. int main () {
  9. pid_t pid;
  10. int shmid;
  11. Char *shm_addr;
  12. Char flag[]= "Parent";
  13. Char Buff[buffer_size];
  14. Create private shared memory for the current process
  15. if ((Shmid=shmget (ipc_private,buffer_size,0666)) <0) {
  16. Perror ("Shmget");
  17. Exit (1);
  18. } else
  19. printf ("Create Shared Memory:%d.\n", Shmid);
  20. IPCS command write to standard output some information about the communication facilities between the active interprocess
  21. -M indicates shared memory
  22. printf ("Created Shared Memory status:\n");
  23. System ("ipcs-m");
  24. if ((Pid=fork ()) <0) {
  25. Perror ("fork");
  26. Exit (1);
  27. }else if (pid==0) {
  28. Automatic allocation of shared memory mapped addresses, readable writable, mapped addresses returned to SHM_ADDR
  29. if ((Shm_addr=shmat (shmid,0,0)) = = (void*)-1) {
  30. Perror ("Child:shmat");
  31. Exit (1);
  32. }else
  33. printf ("Child:attach shared-memory:%p.\n", shm_addr);
  34. printf ("Child Attach Shared Memory status:\n");
  35. System ("ipcs-m");
  36. Compare the characters of shm_addr,flag with the length of strlen (flag)
  37. Returns 0 when its contents are the same
  38. Otherwise return (Str1[n]-str2[n])
  39. while (STRNCMP (Shm_addr,flag,strlen (flag))) {
  40. printf ("Child:waiting for data...\n");
  41. Sleep (10);
  42. }
  43. strcpy (Buff,shm_addr+strlen (flag));
  44. printf ("Child:shared-memory:%s\n", buff);
  45. Delete the shared memory mapped address of the child process
  46. if (SHMDT (SHM_ADDR) <0) {
  47. Perror ("Child:shmdt");
  48. Exit (1);
  49. }else
  50. printf ("Child:deattach shared-memory.\n");
  51. printf ("Child Deattach Shared Memory status:\n");
  52. System ("ipcs-m");
  53. }else{
  54. Sleep (1);
  55. Automatic allocation of shared memory mapped addresses, readable writable, mapped addresses returned to SHM_ADDR
  56. if ((Shm_addr=shmat (shmid,0,0)) = = (void*)-1) {
  57. Perror ("Parent:shmat");
  58. Exit (1);
  59. }else
  60. printf ("Parent:attach shared-memory:%p.\n", shm_addr);
  61. printf ("Parent Attach shared Memory status:\n");
  62. System ("ipcs-m");
  63. Shm_addr to Flag+stdin
  64. Sleep (1);
  65. printf ("\ninput string:\n");
  66. Fgets (Buff,buffer_size-strlen (flag), stdin);
  67. strncpy (Shm_addr,flag,strlen (flag));
  68. strncpy (Shm_addr+strlen (flag), Buff,strlen (buff));
  69. Delete the shared memory mapped address of the parent process
  70. if (SHMDT (SHM_ADDR) <0) {
  71. Perror ("Parent:shmdt");
  72. Exit (1);
  73. }else
  74. printf ("Parent:deattach shared-memory.\n");
  75. printf ("Parent Deattach shared Memory status:\n");
  76. System ("ipcs-m");
  77. Ensures that the child process can read the contents of the shared memory before the parent process deletes the shared memory
  78. Waitpid (pid,null,0);
  79. Delete Shared memory
  80. if (Shmctl (shmid,ipc_rmid,null) ==-1) {
  81. Perror ("Shmct:ipc_rmid");
  82. Exit (1);
  83. }else
  84. printf ("Delete shared-memory.\n");
  85. printf ("Child Delete Shared Memory status:\n");
  86. System ("ipcs-m");
  87. printf ("finished!\n");
  88. }
  89. Exit (0);
  90. }
Copy Code

Operation Result:
$./a.out
Create shared memory:65536.
Created Shared Memory Status:

------Shared Memory Segments--------
Key shmid owner perms bytes nattch Status
0x00000000 65536 Dongxw 666 2048 0

Child:attach shared-memory:0x7fc3519fe000.
Child Attach Shared memory status:

------Shared Memory Segments--------
Key shmid owner perms bytes nattch Status
0x00000000 65536 DONGXW 666 2048 1

Child:waiting for data ...
Parent:attach shared-memory:0x7fc3519fe000.
Parent Attach Shared Memory Status:

------Shared Memory Segments--------
Key shmid owner perms bytes nattch Status
0x00000000 65536 DONGXW 666 2048 2


Input string:
Child:waiting for data ...
Child:waiting for data ...
This is data
Parent:deattach shared-memory.
Parent Deattach Shared Memory Status:

------Shared Memory Segments--------
Key shmid owner perms bytes nattch Status
0x00000000 65536 DONGXW 666 2048 1

Child:shared-memory:this is Data

Child:deattach shared-memory.
Child Deattach Shared memory status:

------Shared Memory Segments--------
Key shmid owner perms bytes nattch Status
0x00000000 65536 Dongxw 666 2048 0

Delete shared-memory.
Child Delete Shared memory status:

------Shared Memory Segments--------
Key shmid owner perms bytes nattch Status

finished!


You can see the red callout data entered from the terminal "This is data", the parent process reads the write to the shared memory area, the child process reads from the shared memory and then displays to the terminal red callout "child:shared-memory:this is Data"

System v Shared memory and code examples for inter-process communication between Linux

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.