Advertisement
Guest User

Untitled

a guest
Mar 19th, 2019
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | None | 0 0
  1. # Shared memory example in python
  2.  
  3. You can allocate shared memory segment that can be accessed from separate
  4. processes.
  5.  
  6. In python, this can be done using `sysv_ipc` module
  7. (`sudo pip install sysv_ipc`).
  8.  
  9. # General idea
  10. One process allocates memory segment, it must define segment size (size must be
  11. multiple of PAGE_SIZE). Segment can then be accessed using unique ID. ID can be
  12. selected randomly.
  13.  
  14. `memory = sysv_ipc.SharedMemory(1235, flags=sysv_ipc.IPC_CREX, size=sysv_ipc.PAGE_SIZE * 4)`
  15.  
  16. When shared memory is no longer needed, it must be freed.
  17.  
  18. `memory.remove()`
  19.  
  20. Other process can then attach to this segment, using ID:
  21.  
  22. `memory = sysv_ipc.SharedMemory(1235)`
  23.  
  24. Each process can then read and write to shared memory.
  25.  
  26. # Example code
  27.  
  28. In the example code, `reader.py` maintains shared memory segment. It allocates
  29. segment on startup and frees it when finishing. It enters infinite loop in which it prints current contents of shared memory segment. Use `^C` to interrupt loop, free memory and exit.
  30.  
  31. `writer.py` can be used to modify contents of memory. It takes address and value as arguments, writes data into segment and exits.
  32.  
  33. Tested on Ubuntu 18.04.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement