a guest Mar 19th, 2019 58 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
- # Shared memory example in python
- You can allocate shared memory segment that can be accessed from separate
- In python, this can be done using `sysv_ipc` module
- (`sudo pip install sysv_ipc`).
- # General idea
- One process allocates memory segment, it must define segment size (size must be
- multiple of PAGE_SIZE). Segment can then be accessed using unique ID. ID can be
- selected randomly.
- `memory = sysv_ipc.SharedMemory(1235, flags=sysv_ipc.IPC_CREX, size=sysv_ipc.PAGE_SIZE * 4)`
- When shared memory is no longer needed, it must be freed.
- Other process can then attach to this segment, using ID:
- `memory = sysv_ipc.SharedMemory(1235)`
- Each process can then read and write to shared memory.
- # Example code
- In the example code, `reader.py` maintains shared memory segment. It allocates
- 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.
- `writer.py` can be used to modify contents of memory. It takes address and value as arguments, writes data into segment and exits.
- Tested on Ubuntu 18.04.
RAW Paste Data