forked from wikimedia/pywikibot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdaemonize.py
67 lines (57 loc) · 1.98 KB
/
daemonize.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
"""Module to daemonize the current process on Unix."""
#
# (C) Pywikibot team, 2007-2022
#
# Distributed under the terms of the MIT license.
#
from __future__ import annotations
import os
import stat
import sys
from pathlib import Path
is_daemon = False
def daemonize(close_fd: bool = True,
chdir: bool = True,
redirect_std: str | None = None) -> None:
"""Daemonize the current process.
Only works on POSIX compatible operating systems.
The process will fork to the background and return control to terminal.
:param close_fd: Close the standard streams and replace them by /dev/null
:param chdir: Change the current working directory to /
:param redirect_std: Filename to redirect stdout and stdin to
"""
# Fork away
if not os.fork():
# Become session leader
os.setsid()
# Fork again to prevent the process from acquiring a
# controlling terminal
pid = os.fork()
if not pid:
global is_daemon
is_daemon = True
if close_fd:
os.close(0)
os.close(1)
os.close(2)
os.open('/dev/null', os.O_RDWR)
if redirect_std:
# R/W mode without execute flags
mode = (stat.S_IRUSR | stat.S_IWUSR
| stat.S_IRGRP | stat.S_IWGRP
| stat.S_IROTH | stat.S_IWOTH)
os.open(redirect_std,
os.O_WRONLY | os.O_APPEND | os.O_CREAT,
mode)
else:
os.dup2(0, 1)
os.dup2(1, 2)
if chdir:
os.chdir('/')
return
# Write out the pid
path = Path(Path(sys.argv[0]).name).with_suffix('.pid')
path.write_text(str(pid), encoding='uft-8')
# Exit to return control to the terminal
# os._exit to prevent the cleanup to run
os._exit(os.EX_OK)