最近在看shadowsocks源代码,关于作者写的启动守护进程的这一块不是很理解:
def daemon_start(pid_file, log_file):
def handle_exit(signum, _):
if signum == signal.SIGTERM:
sys.exit(0)
sys.exit(1)
signal.signal(signal.SIGINT, handle_exit)
signal.signal(signal.SIGTERM, handle_exit)
# fork only once because we are sure parent will exit
pid = os.fork()
assert pid != -1
if pid > 0:
# 这里为什么不是让父进程直接退出,而是等着子进程把自己杀死呢?
time.sleep(5)
sys.exit(0)
# child signals its parent to exit
ppid = os.getppid()
pid = os.getpid()
if write_pid_file(pid_file, pid) != 0:
os.kill(ppid, signal.SIGINT)
sys.exit(1)
os.setsid()
signal.signal(signal.SIGHUP, signal.SIG_IGN)
print('started')
os.kill(ppid, signal.SIGTERM)
我在看APUE关于守护进程编写那一块的时候,书上说的是父进程fork子进程后退出,不知道这里为什么不是直接退出而是等着子进程把自己杀死?
Here, the parent process registers the signal processing function
In order to give the parent process a chance to process the signal sent by the child process, it sleeps for 5 seconds.