DeaD_EyE icon

daemonize is complicated ...

DeaD_EyE | PRO | 06/24/25 06:40:53 PM UTC | 0 ⭐ | 1221 👁️ | Never ⏰ | []
Python |

920 B

|

None

|

0 👍

/

0 👎

import sys
import os
import time
 
# 1. first fork
if os.fork() > 0:
    print("Kill the parent")
    sys.exit(0)
 
# 2. new session
print("setsid")
os.setsid()
 
# 3. second fork
if os.fork() > 0:
    print("Kill the parent")
    sys.exit(0) 
 
# 4. umask
print("umask 0")
os.umask(0)
 
 
print(f"Hello from child: {os.getpid()}")
 
# 5. change working directory
print("chdir /")
os.chdir("/")
 
print("GAG the child process!!!")
 
# 6. flush stdin/stdout/stderr
sys.stdin.flush()
sys.stdout.flush()
sys.stderr.flush()
 
# 7. copy filedescriptor of dev_null to sys.stdin
#    dev_null is closed, but 0 stays open and points to os.devnull
with open(os.devnull, "rb", 0) as dev_null:
    os.dup2(dev_null.fileno(), sys.stdin.fileno())
 
 
with open(os.devnull, "ab", 0) as dev_null:
    os.dup2(dev_null.fileno(), sys.stdout.fileno())
    os.dup2(dev_null.fileno(), sys.stderr.fileno())    
 
 
time.sleep(20)
 

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎