SysV IPC

1.2.0 · active · verified Thu Apr 16

sysv-ipc is a Python library that provides interfaces to System V Inter-Process Communication (IPC) primitives: semaphores, shared memory, and message queues. These mechanisms allow separate processes on the same machine to communicate and synchronize. The current version is 1.2.0, and the project has an active maintenance cadence on GitHub, primarily supporting Python 3.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the creation, acquisition, release, and removal of a semaphore. In a real multi-process application, processes would share a key (e.g., generated by `sysv_ipc.ftok`) to synchronize access to shared resources.

import sysv_ipc
import time
import os

# IPC_PRIVATE creates a new unique semaphore set for demonstration.
# For multi-process communication, use a shared key, e.g.,
# key = sysv_ipc.ftok(os.getcwd(), 1)

try:
    # Create a semaphore set with 1 semaphore, initial value 1.
    # IPC_CREX ensures exclusive creation, raising an error if it exists.
    sem = sysv_ipc.Semaphore(sysv_ipc.IPC_PRIVATE, flags=sysv_ipc.IPC_CREX, initial_value=1)
    print(f"Semaphore created with key: {sem.key}")

    print("Attempting to acquire semaphore...")
    sem.acquire() # Decrement semaphore value by 1
    print("Semaphore acquired. Simulating work...")
    time.sleep(0.5)
    sem.release() # Increment semaphore value by 1
    print("Semaphore released.")

    # It's crucial to remove IPC objects after use to free system resources.
    sem.remove()
    print("Semaphore removed.")

except sysv_ipc.ExistentialError:
    print("Semaphore with this key already exists. This quickstart uses IPC_PRIVATE to avoid conflicts.")
    print("For multi-process, use sysv_ipc.ftok(path, id) for a shared key and omit IPC_CREX.")
except sysv_ipc.Error as e:
    print(f"An IPC error occurred: {e}")

view raw JSON →