fork - Python: Closing file descriptors when daemonizing a process -
i have code in application:
def daemonize_process(stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'): ''' fork current process daemon (background process), redirecting standard file descriptors @param string stdin standard input file name @param string stdout standard output file name @param string stderr standard error file name ''' # transform process in daemon, necessary fork, decouple # parent environment, fork 1 time again , close opened file descriptors. # first fork try: pid = os.fork() if pid > 0: # exit first parent process # using os._exit() instead of sys.exit() in kid process after # fork recommended python api docs os._exit(0) except oserror e: sys.stderr.write("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror)) sys.exit(1) # decouple parent environment os.chdir("/") os.umask(0) os.setsid() # sec fork try: pid = os.fork() if pid > 0: # exit sec parent process # using os._exit() instead of sys.exit() in kid process after # fork recommended python api docs os._exit(0) except oserror, e: sys.stderr.write("fork #2 failed: (%d) %s\n" % (e.errno, e.strerror)) sys.exit(1) # close file descriptors import resource maxfd = resource.getrlimit(resource.rlimit_nofile)[1] if (maxfd == resource.rlim_infinity): maxfd = 1024 fd in range(0, maxfd): try: os.close(fd) except oserror: sys.stderr.write("error closing file: (%d) %s\n" % (e.errno, e.strerror)) pass # process daemonized, redirect standard file descriptors. f in sys.stdout, sys.stderr: f.flush( ) si = file(stdin, 'r') = file(stdout, 'a+') se = file(stderr, 'a+', 0) os.dup2(si.fileno( ), sys.stdin.fileno( )) os.dup2(so.fileno( ), sys.stdout.fileno( )) os.dup2(se.fileno( ), sys.stderr.fileno( )) in daemonization code have seen in web, file descriptors not closed in kid process. why should this? seems me may want maintain working in files working before fork-detach-fork process.
thanks in advance.
why close file descriptors? can assume process launching daemon knows it's doing , close file descriptors before exec().
for illustration if run bash, open file descriptors get, standard ones, plus redirection manually set in shell.
if programme leaves file descriptors open around, it's buggy. anyway possible open files using fd_cloexec, automatically closed on exec().
python fork daemon
No comments:
Post a Comment