Creates a new shared memory block or attaches to an existing shared memory block. Every shared memory block is assigned a unique name. This enables one process to create a shared memory block with a particular name so that a different process can attach to that same shared memory
| 48 | |
| 49 | |
| 50 | class SharedMemory: |
| 51 | """Creates a new shared memory block or attaches to an existing |
| 52 | shared memory block. |
| 53 | |
| 54 | Every shared memory block is assigned a unique name. This enables |
| 55 | one process to create a shared memory block with a particular name |
| 56 | so that a different process can attach to that same shared memory |
| 57 | block using that same name. |
| 58 | |
| 59 | As a resource for sharing data across processes, shared memory blocks |
| 60 | may outlive the original process that created them. When one process |
| 61 | no longer needs access to a shared memory block that might still be |
| 62 | needed by other processes, the close() method should be called. |
| 63 | When a shared memory block is no longer needed by any process, the |
| 64 | unlink() method should be called to ensure proper cleanup.""" |
| 65 | |
| 66 | # Defaults; enables close() and unlink() to run without errors. |
| 67 | _name = None |
| 68 | _fd = -1 |
| 69 | _mmap = None |
| 70 | _buf = None |
| 71 | _flags = os.O_RDWR |
| 72 | _mode = 0o600 |
| 73 | _prepend_leading_slash = True if _USE_POSIX else False |
| 74 | _track = True |
| 75 | |
| 76 | def __init__(self, name=None, create=False, size=0, *, track=True): |
| 77 | if not size >= 0: |
| 78 | raise ValueError("'size' must be a positive integer") |
| 79 | if create: |
| 80 | self._flags = _O_CREX | os.O_RDWR |
| 81 | if size == 0: |
| 82 | raise ValueError("'size' must be a positive number different from zero") |
| 83 | if name is None and not self._flags & os.O_EXCL: |
| 84 | raise ValueError("'name' can only be None if create=True") |
| 85 | |
| 86 | self._track = track |
| 87 | if _USE_POSIX: |
| 88 | |
| 89 | # POSIX Shared Memory |
| 90 | |
| 91 | if name is None: |
| 92 | while True: |
| 93 | name = _make_filename() |
| 94 | try: |
| 95 | self._fd = _posixshmem.shm_open( |
| 96 | name, |
| 97 | self._flags, |
| 98 | mode=self._mode |
| 99 | ) |
| 100 | except FileExistsError: |
| 101 | continue |
| 102 | self._name = name |
| 103 | break |
| 104 | else: |
| 105 | name = "/" + name if self._prepend_leading_slash else name |
| 106 | self._fd = _posixshmem.shm_open( |
| 107 | name, |