diff --git a/src/jianda_proxy/cli.py b/src/jianda_proxy/cli.py index 1e00f00..05fae93 100644 --- a/src/jianda_proxy/cli.py +++ b/src/jianda_proxy/cli.py @@ -30,6 +30,7 @@ def build_parser(): p_start = sub.add_parser("start", help="Start the proxy daemon") p_start.add_argument("--foreground", action="store_true", help="Run in foreground (no daemon)") p_start.add_argument("--port", type=str, default=None, help="Override listen port") + p_start.add_argument("--_daemon_child", action="store_true", help=argparse.SUPPRESS) # stop sub.add_parser("stop", help="Stop the proxy daemon") @@ -67,8 +68,11 @@ def cmd_start(args): if args.foreground: _run_foreground(config_dict) + elif args._daemon_child: + _run_child(config_dict) else: - _run_daemonized(config_dict) + daemonize() + _run_child(config_dict) def _run_foreground(config_dict): @@ -85,7 +89,7 @@ def _run_foreground(config_dict): server.server_close() -def _run_daemonized(config_dict): +def _run_child(config_dict): from logging.handlers import RotatingFileHandler log_path = get_log_path() @@ -97,8 +101,6 @@ def _run_daemonized(config_dict): root.setLevel(logging.INFO) root.addHandler(handler) - daemonize() - pid = os.getpid() write_pid(pid) diff --git a/src/jianda_proxy/daemon.py b/src/jianda_proxy/daemon.py index 3b3819f..1729707 100644 --- a/src/jianda_proxy/daemon.py +++ b/src/jianda_proxy/daemon.py @@ -111,14 +111,16 @@ def daemonize(): import subprocess creation_flags = subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.DETACHED_PROCESS + cmd = [sys.executable, "-m", "jianda_proxy"] + sys.argv[1:] + ["--_daemon_child"] subprocess.Popen( - [sys.executable] + sys.argv + ["--_daemon_child"], + cmd, creationflags=creation_flags, close_fds=True, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) + sys.exit(0) else: pid = os.fork() if pid > 0: