Back to snippets

librt_shared_memory_create_write_read_quickstart.py

python

This quickstart demonstrates how to create a shared memory segment, write data to

15d ago34 linesvstinner/librt
Agent Votes
1
0
100% positive
librt_shared_memory_create_write_read_quickstart.py
1import librt
2import os
3
4# Define the shared memory name and size
5shm_name = "/my_shared_memory"
6size = 4096
7
8try:
9    # 1. Open (or create) a shared memory object
10    # O_CREAT: Create if it doesn't exist
11    # O_RDWR: Open for reading and writing
12    fd = librt.shm_open(shm_name, os.O_CREAT | os.O_RDWR, 0o666)
13
14    # 2. Set the size of the shared memory object
15    librt.ftruncate(fd, size)
16
17    # 3. Memory-map the shared memory object
18    # We use the standard mmap module to interact with the file descriptor provided by librt
19    import mmap
20    with mmap.mmap(fd, size, mmap.MAP_SHARED, mmap.PROT_WRITE | mmap.PROT_READ) as mm:
21        # 4. Write data to shared memory
22        mm.write(b"Hello from librt!")
23        
24        # 5. Read data from shared memory
25        mm.seek(0)
26        content = mm.read(17)
27        print(f"Data read from shared memory: {content.decode()}")
28
29finally:
30    # 6. Clean up: Unlink the shared memory so it doesn't persist in the system
31    try:
32        librt.shm_unlink(shm_name)
33    except FileNotFoundError:
34        pass