-
-
Save heiner/c681ef83e8b38ae5c0fb6cd9a26cc046 to your computer and use it in GitHub Desktop.
Some Python ctypes-based POSIX shared memory functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import sys | |
try: | |
from _posixshmem import shm_open, shm_unlink | |
except ImportError: | |
import ctypes | |
dllname = None | |
if sys.platform.startswith("linux"): | |
dllname = "librt.so" | |
rtld = ctypes.CDLL(dllname, use_errno=True) | |
def shm_open(name, flags, mode): | |
if isinstance(name, str): | |
name = name.encode() | |
buf = ctypes.create_string_buffer(name) | |
result = rtld.shm_open(buf, ctypes.c_int(flags), ctypes.c_ushort(mode)) | |
if result == -1: | |
errno = ctypes.get_errno() | |
raise OSError(errno, os.strerror(errno), name.decode()) | |
return result | |
def shm_unlink(name): | |
if isinstance(name, str): | |
name = name.encode() | |
buf = ctypes.create_string_buffer(name) | |
result = rtld.shm_unlink(buf) | |
if result == -1: | |
errno = ctypes.get_errno() | |
raise OSError(errno, os.strerror(errno), name.decode()) | |
def main(): | |
name = "/myshm" | |
f = shm_open(name, flags=os.O_RDWR | os.O_CREAT | os.O_EXCL, mode=0o666) | |
print(f, name) | |
shm_unlink(name) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment