Linux inter-process communication-shared memory

Source: Internet
Author: User

Shared memory is the fastest way to communicate between processes running on the same machine, because data does not need to be copied between different processes. A shared memory area is usually created by a process, and other processes read and write this memory area. Shared Memory is often used in conjunction with other communication mechanisms, such as semaphores, to achieve synchronization and mutual exclusion between processes.
The first function to use is shmget, which obtains a shared storage identifier.

# I nclude <sys/types. h>
# I nclude <sys/IPC. h>
# I nclude <sys/SHM. h>
Int shmget (key_t key, int size, int flag );

This function is similar to the familiar malloc function. The system allocates the size of memory as the shared memory according to the request. In the Linux kernel, each IPC structure has a non-negative integer identifier, So that you only need to reference the identifier when sending a message to a message queue. This identifier is obtained by the key word of the IPC structure in the kernel. This keyword is the key of the first function above. The data type key_t is defined in the header file SYS/types. H. It is a long integer data. In our subsequent chapters, we will also encounter this keyword.

After the shared memory is created, other processes can call shmat () to connect it to their own address space.

Void * shmat (INT shmid, void * ADDR, int flag );

Shmid is the shared storage identifier returned by the shmget function. The ADDR and flag parameters determine how to determine the connection address. the return value of the function is the actual address connected to the Data Segment of the process, A process can perform read/write operations on the process.

When using shared storage to implement inter-process communication, note the synchronization of data access. Make sure that the desired data has been written when a process reads data. Generally, semaphores are used to synchronize access to shared storage data. In addition, you can use the shmctl function to set some flags of shared storage memory, such as shm_lock and shm_unlock.

The shared memory mechanism allows two unrelated processes to read and modify the same memory segment for data sharing. Main Function Definition:

# Include <sys/SHM. h>

Void * shmat (INT shm_id, const void * shm_addr, int shmflg );

Int shmctl (INT shm_id, int cmd, struct shmid_ds * BUF );

Int shmdt (const void * shm_addr );

Int shmget (key_t key, size_t size, int shmflag );

C code

  1. /* Server. C: write people to the shared memory */
  2. # Include <stdio. h>
  3. # Include <sys/types. h>
  4. # Include <sys/IPC. h>
  5. # Include <sys/SEM. h>
  6. Int main ()
  7. {
  8. Struct people {
  9. Char name [10];
  10. Int age;
  11. };
  12. Int Semid;
  13. Int shmid;
  14. Key_t semkey;
  15. Key_t shmkey;
  16. Semkey = ftok ("server. c", 0 );
  17. Shmkey = ftok ("client. c", 0 );
  18. /* Create an IPC for shared memory and semaphores */
  19. Semid = semget (semkey, 1,0666 | ipc_creat );
  20. If (Semid =-1)
  21. Printf ("creat SEM is fail \ n ");
  22. Shmid = shmget (shmkey, | ipc_creat );
  23. If (shmid =-1)
  24. Printf ("creat SHM is fail \ n ");
  25. /* Set the initial semaphore value, that is, the number of resources */
  26. Union semun {
  27. Int val;
  28. Struct semid_ds * Buf;
  29. Ushort * array;
  30. } Sem_u;
  31. Sem_u.val = 1;
  32. Semctl (Semid, 0, setval, sem_u );
  33. /* Map the shared memory to the address of the current process, and then directly perform the ADDR operation on the address in the process */
  34. Struct people * ADDR;
  35. ADDR = (struct people *) shmat (shmid, 0, 0 );
  36. If (ADDR = (struct people *)-1)
  37. Printf ("SHM shmat is fail \ n ");
  38. /* P operations on semaphores */
  39. Void P ()
  40. {
  41. Struct sembuf sem_p;
  42. Sem_p.sem_num = 0;
  43. Sem_p.sem_op =-1;
  44. If (semop (Semid, & sem_p, 1) =-1)
  45. Printf ("P operation is fail \ n ");
  46. }
  47. /* Semaphore v operation */
  48. Void V ()
  49. {
  50. Struct sembuf sem_v;
  51. Sem_v.sem_num = 0;
  52. Sem_v.sem_op = 1;
  53. If (semop (Semid, & sem_v, 1) =-1)
  54. Printf ("V operation is fail \ n ");
  55. }
  56. /* Write data to the shared memory */
  57. P ();
  58. Strcpy (* ADDR). Name, "Xiaoming ");
  59. /* Note: ① A value can only be assigned to the address pointed to by the pointer. You cannot define a struct people people_1; ADDR = & people_1; Because ADDR is at ADDR = (struct people *) shmat (shmid,);, the system has automatically assigned an address, this address is associated with the shared memory, so you cannot change the pointer to this address, otherwise, he will not point to the shared memory and cannot complete the communication.
  60. Note: ② assign values to character arrays. Just now, it's so cool .. */
  61. (* ADDR). Age = 10;
  62. V ();
  63. /* Disconnect the shared memory from the current process */
  64. If (shmdt (ADDR) =-1)
  65. Printf ("shmdt is fail \ n ");
  66. }

C code

  1. /* Client. C: Read people from the shared memory */
  2. # Include <stdio. h>
  3. # Include <sys/types. h>
  4. # Include <sys/IPC. h>
  5. # Include <sys/SEM. h>
  6. Int main ()
  7. {
  8. Int Semid;
  9. Int shmid;
  10. Key_t semkey;
  11. Key_t shmkey;
  12. Semkey = ftok ("server. c", 0 );
  13. Shmkey = ftok ("client. c", 0 );
  14. Struct people {
  15. Char name [10];
  16. Int age;
  17. };
  18. /* Read the IPC of the shared memory and semaphore */
  19. Semid = semget (semkey, 0, 0666 );
  20. If (Semid =-1)
  21. Printf ("creat SEM is fail \ n ");
  22. Shmid = shmget (shmkey, 0, 0666 );
  23. If (shmid =-1)
  24. Printf ("creat SHM is fail \ n ");
  25. /* Map the shared memory to the address of the current process, and then directly perform the ADDR operation on the address in the process */
  26. Struct people * ADDR;
  27. ADDR = (struct people *) shmat (shmid, 0, 0 );
  28. If (ADDR = (struct people *)-1)
  29. Printf ("SHM shmat is fail \ n ");
  30. /* P operations on semaphores */
  31. Void P ()
  32. {
  33. Struct sembuf sem_p;
  34. Sem_p.sem_num = 0;
  35. Sem_p.sem_op =-1;
  36. If (semop (Semid, & sem_p, 1) =-1)
  37. Printf ("P operation is fail \ n ");
  38. }
  39. /* Semaphore v operation */
  40. Void V ()
  41. {
  42. Struct sembuf sem_v;
  43. Sem_v.sem_num = 0;
  44. Sem_v.sem_op = 1;
  45. If (semop (Semid, & sem_v, 1) =-1)
  46. Printf ("V operation is fail \ n ");
  47. }
  48. /* Read data from the shared memory */
  49. P ();
  50. Printf ("Name: % s \ n", ADDR-> name );
  51. Printf ("Age: % d \ n", ADDR-> age );
  52. V ();
  53. /* Disconnect the shared memory from the current process */
  54. If (shmdt (ADDR) =-1)
  55. Printf ("shmdt is fail \ n ");
  56. /* The IPC must be deleted. Otherwise it will remain in the system */
  57. If (semctl (Semid, 0, ipc_rmid, 0) =-1)
  58. Printf ("semctl delete error \ n ");
  59. If (shmctl (shmid, ipc_rmid, null) =-1)
  60. Printf ("shmctl delete error \ n ");
  61. }

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.