DeaD_EyE

daemonize is complicated ...

Jun 24th, 2025
1,326
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.92 KB | None | 0 0
  1. import sys
  2. import os
  3. import time
  4.  
  5. # 1. first fork
  6. if os.fork() > 0:
  7.     print("Kill the parent")
  8.     sys.exit(0)
  9.  
  10. # 2. new session
  11. print("setsid")
  12. os.setsid()
  13.  
  14. # 3. second fork
  15. if os.fork() > 0:
  16.     print("Kill the parent")
  17.     sys.exit(0)
  18.  
  19. # 4. umask
  20. print("umask 0")
  21. os.umask(0)
  22.  
  23.  
  24. print(f"Hello from child: {os.getpid()}")
  25.  
  26. # 5. change working directory
  27. print("chdir /")
  28. os.chdir("/")
  29.  
  30. print("GAG the child process!!!")
  31.  
  32. # 6. flush stdin/stdout/stderr
  33. sys.stdin.flush()
  34. sys.stdout.flush()
  35. sys.stderr.flush()
  36.  
  37. # 7. copy filedescriptor of dev_null to sys.stdin
  38. #    dev_null is closed, but 0 stays open and points to os.devnull
  39. with open(os.devnull, "rb", 0) as dev_null:
  40.     os.dup2(dev_null.fileno(), sys.stdin.fileno())
  41.  
  42.  
  43. with open(os.devnull, "ab", 0) as dev_null:
  44.     os.dup2(dev_null.fileno(), sys.stdout.fileno())
  45.     os.dup2(dev_null.fileno(), sys.stderr.fileno())    
  46.  
  47.  
  48. time.sleep(20)
  49.  
Advertisement
Comments
  • User was banned
Add Comment
Please, Sign In to add comment