Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Daemonize

 Daemonize

A little tech talk for rannts#16 meetup on correct daemonization in UNIXes before systed era

Sergey Arkhipov

May 20, 2017
Tweet

More Decks by Sergey Arkhipov

Other Decks in Programming

Transcript

  1. Чего хотим #!/usr/bin/env python3 # -*- coding: utf-8 -*- import

    contextlib import syslog import time @contextlib.contextmanager def daemonize(): yield if __name__ == "__main__": with daemonize(): syslog.openlog(facility=syslog.LOG_USER) syslog.syslog("Daemon start.") time.sleep(10) syslog.syslog("Daemon done.")
  2. Подход 2 def daemonize(): first_pid = os.fork() if first_pid: sys.exit(0)

    syslog.syslog("Session={0}, Group={1}, Parent={2}, Self={3}".format( os.getsid(0), os.getpgid(0), os.getppid(), os.getpid() )) yield … Session=7087, Group=14115, Parent=14115, Self=14151 … Daemon start. … Daemon done.
  3. Подход 2 def daemonize(): first_pid = os.fork() if first_pid: sys.exit(0)

    syslog.syslog("Session={0}, Group={1}, Parent={2}, Self={3}".format( os.getsid(0), os.getpgid(0), os.getppid(), os.getpid() )) os.setsid() syslog.syslog("Session={0}, Group={1}, Parent={2}, Self={3}".format( os.getsid(0), os.getpgid(0), os.getppid(), os.getpid() )) yield … Session=7087, Group=17364, Parent=17364, Self=17400 … Session=17400, Group=17400, Parent=17364, Self=17400 … Daemon start … Daemon done.
  4. Подход 5 def daemonize(): if os.fork(): sys.exit(0) os.setsid() if os.fork():

    sys.exit(0) os.chdir("/") os.umask(0o002) sys.stdout.flush() sys.stderr.flush() _, max_fds = resource.getrlimit(resource.RLIMIT_NOFILE) max_fds = max_fds if max_fds!=resource.RLIM_INFINITY else 1024 os.closerange(0, max_fds) sys.stdout = sys.stderr = open(os.devnull, "w") sys.stdin = open(os.devnull, "r") yield
  5. Подход 6 def daemonize(): if os.getppid() != 1: return if

    os.fork(): sys.exit(0) os.setsid() if os.fork(): sys.exit(0) os.chdir("/") os.umask(0o002) sys.stdout.flush() sys.stderr.flush() _, max_fds = resource.getrlimit(resource.RLIMIT_NOFILE) max_fds = max_fds if max_fds != resource.RLIM_INFINITY else 1024 os.closerange(0, max_fds) sys.stdout = sys.stderr = open(os.devnull, "w") sys.stdin = open(os.devnull, "r") yield
  6. def daemonize(): if os.getppid() != 1: return if os.fork(): sys.exit(0)

    os.setsid() if os.fork(): sys.exit(0) os.chdir("/") os.umask(0o002) sys.stdout.flush() sys.stderr.flush() _, max_fds = resource.getrlimit(resource.RLIMIT_NOFILE) max_fds = max_fds if max_fds != resource.RLIM_INFINITY else 1024 os.closerange(0, max_fds) sys.stdout = sys.stderr = open(os.devnull, "w") sys.stdin = open(os.devnull, "r") yield