Python Glossary Русский

all Python 3Linux · macOSosfunction

os.setsid

os — sessions and process groups

Create a new session with the process as leader (detach from terminal). Availability: Unix.

Syntax

os.setsid(...)

A group leader cannot call it — it raises PermissionError — so the usual pattern is fork first, then setsid in the child. The new session has no controlling terminal, so closing the terminal no longer kills the process with SIGHUP. subprocess offers the same via start_new_session=True.

Examples

import os
pid = os.fork()                          # → ? только Unix: 0 в дочернем процессе, PID ребёнка — в родительском
if pid == 0: print(os.setsid())          # → None — ребёнок стал лидером новой сессии и отвязался от терминала
print(os.getsid(0) == os.getpid())       # → ? True в ребёнке после setsid: id сессии совпадает с его PID
print(os.getpgrp() == os.getpid())       # → ? True: setsid заодно создаёт новую группу процессов с тем же id
os.setsid()                              # → PermissionError: процесс уже лидер группы, повторный вызов запрещён

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy