Communication between Linux processes (C): Shared memory

Source: Internet
Author: User
Tags semaphore

introduction of Shared memoryshared memory is one of three IPC (inter-process communication) mechanisms. It allows two unrelated processes to access the same logical memory. shared memory is a very efficient way to pass data between two processes that are in progress. most of the shared memory implementations,all of the memory shared between different processes is scheduled for the same piece of physical memory .  shared Memory is a special range of addresses created by IPC for a process,it will appear in the address space of the process. Other processes can connect the same piece of shared memory to their own address space. all processes have access to the addresses in the shared memory,As if they were allocated by malloc.  If a process writes data to the shared memory,The changes are immediately visible to any other process that can access the same piece of shared memory.   second, the synchronization of shared memoryShared memory provides an effective way to share and deliver data between multiple processes. but it does not provide a synchronization mechanism ,so we usually need to use other mechanisms to synchronize access to shared memory. we typically use shared memory to provide effective access to large chunks of memory,Simultaneous access to the memory is synchronized by passing small messages.  before the first process ends a write operation to the shared memory,There is no automatic mechanism to prevent the second process from starting to read it. The synchronization control of shared memory access must be the responsibility of the programmer.  shows how shared memory is co-existing: the arrows in the diagram show the mapping of the logical address space of each process to the available physical memory.    Iii. functions used for shared memory
    1. #include <sys/shm.h>
    2. int Shmget (key_t key, size_t size, int shmflg);
    3. void *shmat (int shm_id, const void *shm_addr, int shmflg);
    4. int SHMDT (const void *SHM_ADDR);
    5. int shmctl (int shm_id, int cmd, struct shmid_ds *buf);
1. Shmget functionThis function is used to create shared memory :
    1. int Shmget (key_t key, size_t size, int shmflg);
Parameters:key: As with the semaphore, the program needs to provide a parameter key,it effectively names the shared memory segment.       There is a special key value of Ipc_private,It is used to create a shared memory that is only part of the creation process.usually not used. Size: Specifies the amount of memory that needs to be shared in bytes. Shmflag: A permission flag with 9 bits,They work the same as the mode flag used when creating the file. a special bit, defined by ipc_creat, must be a bitwise OR of a permission flag.to create a new shared memory segment.  Note:the permission flags are useful for shared memory,because it allows a process to create shared memory that can be written by a process owned by the creator of the shared memory,simultaneous processes created by other users can read only shared memory.  We can use this feature to provide an effective way to read-only access to the data,by putting the data into shared memory and setting its permissions,you can avoid data being modified by other users.  return Value:a non-negative integer, the shared memory identifier , is returned when the creation is successful;if it fails, -1 is returned.  2. Shmat functionWhen you create a shared memory segment for the first time, it cannot be accessed by any process. To initiate access to this memory,it must be connected to the address space of a process . This work is done by the Shmat function:
    1. void *shmat (int shm_id, const void *shm_addr, int shmflg);
Parameters:shm_id: The shared memory identity returned by Shmget. Shm_add: Specifies the address location of the shared memory connection to the current process. It is usually a null pointer,represents an address that allows the system to select shared memory. SHMFLG: Is a set of flags. its two possible values are:Shm_rnd, used in conjunction with Shm_add,the address used to control the shared memory connection. Shm_rdonly, which makes the connected memory read-only         return Value:If the call succeeds, returns a pointer to the first byte of the shared memory;If it fails, returns -1. Read and write access to shared memory is owned by its owner (the creator of Shared memory),its access rights and the owner decision of the current process. access to shared memory is similar to a file's access rights.   3. Shmdt separates shared memory from the current process .
    1. int SHMDT (const void *SHM_ADDR);
The address pointer returned by the Shm_addr:shmat.  when successful, returns 0,when failed, returns -1. Note:shared memory separation did not delete it.only makes the shared memory no longer available to the current process.   4. Shmctlcontrol functions for shared memory
    1. int shmctl (int shm_id, int cmd, struct shmid_ds *buf);
The SHMID_DS structure contains at least the following members:
    1. struct Shmid_ds {
    2. uid_t Shm_perm.uid;
    3. uid_t Shm_perm.gid;
    4. mode_t Shm_perm.mode;
    5. }
 Parameters:shm_id: Is the shared memory identifier returned by Shmget. command: Is the action to be taken,it can fetch 3 values:  ipc_stat Sets the data in the SHMID_DS structure to the current associated value of shared memory Ipc_set If the process has sufficient permissions,Set the current association value of shared memory to the value given in the SHMID_DS structure ipc_rmid Deleting shared memory segments buf: Is a pointer,a structure that contains shared memory mode and access rights.  return Value:when successful, returns 0,when failed, returns -1.  Iv. ExamplesA typical consumer-producer program,the first program (consumer) creates a shared memory segment,then the data written into it is displayed. the second program (producer) will connect an existing shared memory segment,and allows us to enter data into it.  shm_com.h
    1. #define TEXT_SZ 2048
    2. struct Shared_use_st {
    3. int written_by_you;
    4. Char SOME_TEXT[TEXT_SZ];
    5. };
when there is data written into this structure,We use the Written_by_you logo in the structure to inform the consumer. The length of text that needs to be transferred 2K is arbitrary.  shm1.c Consumer Program
  1. #include <unistd.h>
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. #include <string.h>
  5. #include <sys/shm.h>
  6. #include "shm_com.h"
  7. int main ()
  8. {
  9. int running = 1;
  10. void *shared_memory = (void *) 0;
  11. struct Shared_use_st *shared_stuff;
  12. int shmid;
  13. Srand ((unsigned int) getpid ());
  14. Shmid = shmget((key_t) 1234, sizeof (struct shared_use_st), 0666 | Ipc_creat);
  15. if (Shmid = =-1) {
  16. fprintf (stderr, "Shmget failed\n");
  17. Exit (Exit_failure);
  18. }
 now, let the program have access to this shared memory:
    1. Shared_memory = Shmat(Shmid, (void *) 0, 0);
    2. if (shared_memory = = (void *)-1) {
    3. fprintf (stderr, "Shmat failed\n");
    4. Exit (Exit_failure);
    5. }
    6. printf ("Memory attached at%x\n", (int) shared_memory);
 The next part of the program assigns Shared_memory to Shared_stuff,It then outputs the text in the written_by_you. The loop will be executed until the end string is found in written_by_you. sleep calls forcing the consumer program to stay a little more in the critical area,Let the producer program wait:
  1. Shared_stuff = (struct Shared_use_st *) shared_memory;
  2. shared_stuff->written_by_you = 0;
  3. while (running)
  4. {
  5. if (shared_stuff->written_by_you)
  6. {
  7. printf ("You wrote:%s", shared_stuff->some_text);
  8. Sleep (rand ()% 4); /* Make the other process wait for us! * /
  9. shared_stuff->written_by_you = 0;
  10. if (strncmp (Shared_stuff->some_text, "End", 3) = = 0) {
  11. running = 0;
  12. }
  13. }
  14. }
 Finally, the shared memory is detached and then deleted:
    1. if (shmdt(shared_memory) = =-1)
    2. {
    3. fprintf (stderr, "Shmdt failed\n");
    4. Exit (Exit_failure);
    5. }
    6. if (shmctl(shmid, ipc_rmid, 0) = =-1)
    7. {
    8. fprintf (stderr, "Shmctl (ipc_rmid) failed\n");
    9. Exit (Exit_failure);
    10. }
    11. Exit (exit_success);
    12. }
shm2.c Producer Programit uses it to enter data into the consumer program.
  1. #include <unistd.h>
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. #include <string.h>
  5. #include <sys/shm.h>
  6. #include "shm_com.h"
  7. int main ()
  8. {
  9. int running = 1;
  10. void *shared_memory = (void *) 0;
  11. struct Shared_use_st *shared_stuff;
  12. Char Buffer[bufsiz];
  13. int shmid;
  14. Shmid = shmget((key_t) 1234, sizeof (struct shared_use_st), 0666 | Ipc_creat);
  15. if (Shmid = =-1)
  16. {
  17. fprintf (stderr, "Shmget failed\n");
  18. Exit (Exit_failure);
  19. }
  20. Shared_memory = Shmat(Shmid, (void *) 0, 0);
  21. if (shared_memory = = (void *)-1)
  22. {
  23. fprintf (stderr, "Shmat failed\n");
  24. Exit (Exit_failure);
  25. }
  26. printf ("Memory attached at%x\n", (int) shared_memory);
  27. Shared_stuff = (struct Shared_use_st *) shared_memory;
  28. while (running)
  29. {
  30. while (shared_stuff->written_by_you = = 1)
  31. {
  32. Sleep (1);
  33. printf ("Waiting for client...\n");
  34. }
  35. printf ("Enter some text:");
  36. Fgets (buffer, bufsiz, stdin);
  37. strncpy (shared_stuff->some_text, buffer, TEXT_SZ);
  38. Shared_stuff->written_by_you = 1;
  39. if (strncmp (buffer, "End", 3) = = 0) {
  40. running = 0;
  41. }
  42. }
  43. if (shmdt(shared_memory) = =-1) {
  44. fprintf (stderr, "Shmdt failed\n");
  45. Exit (Exit_failure);
  46. }
  47. Exit (exit_success);
  48. }
Run the program,you will see the sample output as follows:
    1. $./SHM1 &
    2. [1] 294
    3. Memory attached at 40017000
    4. $./shm2
    5. Memory attached at 40017000
    6. Enter some Text:hello
    7. You Wrote:hello
    8. Waiting for client ...
    9. Waiting for client ...
    10. Enter some text:
    11. You wrote:
    12. Waiting for client ...
    13. Waiting for client ...
    14. Waiting for client ...
    15. Enter some Text:end
    16. You wrote:end
    17. $
Program parsing:Consumer ProgramsCreate a shared memory segment,then connect it to its own address space,and,we used a struct shared_use_st at the beginning of shared memory.There is a sign written_by_you in the structure,This flag is set when there is data written in the shared memory.  when this flag is set,The program reads the text from the shared memory,print it out,then clear this flag to indicate that the data has been read. we use a special string end to exit the loop.  Next,The program detaches the shared memory segment and deletes it.  producer Proceduresuse the same key value 1234来 to get and connect to the same shared memory segment,The user is then prompted to enter some text. if the flag written_by_you is set,producers know that the consumption process has not finished reading the last data,so just keep waiting. when the other process clears the flag,The producer writes the new data and sets the flag. It also uses the string end to terminate and detach shared memory segments.  the synchronization flags provided here are written_by_you,It is a very inefficient busy wait (keeps looping).  but in actual programming,The semaphore should be used,or by passing messages (using pipelines or IPC messages),or generate signalsmethod to provide a more efficient synchronization mechanism between read and write.

Communication between Linux processes (C): 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.