diff options
Diffstat (limited to 'unix_doublefork.py')
-rw-r--r-- | unix_doublefork.py | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/unix_doublefork.py b/unix_doublefork.py new file mode 100644 index 0000000..fc94a42 --- /dev/null +++ b/unix_doublefork.py @@ -0,0 +1,37 @@ +# -*- coding: utf-8 -*- +"""Example of the Unix double fork for daemons.""" +import os +import sys + + +def print_process_info(name): + """Print information about the currently executing process.""" + pid = os.getpid() + pgid = os.getpgid(pid) + sid = os.getsid(pid) + print('{} (PID:{}) (PGID:{}) (SID:{})'.format(name, pid, pgid, sid)) + + +# First Fork +newpid = os.fork() +if newpid > 0: + print_process_info('Parent') + sys.exit() +else: + print_process_info('Child') + os.setsid() + newpid = os.fork() + # Second fork + if newpid == 0: + print_process_info('Grandchild') + else: + print_process_info('Child') + sys.exit() + +# # POP QUIZ!!!! Why won't this work +# print_process_info('Parent') +# os.setsid() +# print_process_info('Parent') +# newpid = os.fork() +# if newpid == 0: +# print_process_info('Child') |