From e065b1dfba5aa3d214922bb4f2777a181a87a437 Mon Sep 17 00:00:00 2001 From: xiongziliang <771730766@qq.com> Date: Sat, 9 Apr 2022 21:02:54 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AD=90=E8=BF=9B=E7=A8=8B=E9=87=8D=E5=90=AF?= =?UTF-8?q?=E5=A4=B1=E8=B4=A5=E6=97=B6=EF=BC=8C=E4=B8=8D=E5=BA=94=E9=80=9A?= =?UTF-8?q?=E7=9F=A5=E5=AE=88=E6=8A=A4=E8=BF=9B=E7=A8=8B=E9=80=80=E5=87=BA?= =?UTF-8?q?=EF=BC=8C=E7=A1=AE=E4=BF=9D=E5=AD=90=E8=BF=9B=E7=A8=8B=E9=87=8D?= =?UTF-8?q?=E5=90=AF=E6=88=90=E5=8A=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- server/System.cpp | 23 +++++++++++++---------- server/System.h | 2 +- server/main.cpp | 6 ++++-- 3 files changed, 18 insertions(+), 13 deletions(-) diff --git a/server/System.cpp b/server/System.cpp index 200a0ea5..9b744230 100644 --- a/server/System.cpp +++ b/server/System.cpp @@ -81,42 +81,45 @@ static void sig_crash(int sig) { #endif // !defined(ANDROID) && !defined(_WIN32) -void System::startDaemon() { +void System::startDaemon(bool &kill_parent_if_failed) { + kill_parent_if_failed = true; #ifndef _WIN32 static pid_t pid; - do{ + do { pid = fork(); - if(pid == -1){ + if (pid == -1) { WarnL << "fork失败:" << get_uv_errmsg(); //休眠1秒再试 sleep(1); continue; } - if(pid == 0){ + if (pid == 0) { //子进程 return; } //父进程,监视子进程是否退出 - DebugL << "启动子进程:" << pid; + DebugL << "启动子进程:" << pid; signal(SIGINT, [](int) { WarnL << "收到主动退出信号,关闭父进程与子进程"; - kill(pid,SIGINT); + kill(pid, SIGINT); exit(0); }); - do{ + do { int status = 0; - if(waitpid(pid, &status, 0) >= 0) { + if (waitpid(pid, &status, 0) >= 0) { WarnL << "子进程退出"; //休眠3秒再启动子进程 sleep(3); + //重启子进程,如果子进程重启失败,那么不应该杀掉守护进程,这样守护进程可以一直尝试重启子进程 + kill_parent_if_failed = false; break; } DebugL << "waitpid被中断:" << get_uv_errmsg(); - }while (true); - }while (true); + } while (true); + } while (true); #endif // _WIN32 } diff --git a/server/System.h b/server/System.h index ac679fac..9ca6fda0 100644 --- a/server/System.h +++ b/server/System.h @@ -16,7 +16,7 @@ class System { public: static std::string execute(const std::string &cmd); - static void startDaemon(); + static void startDaemon(bool &kill_parent_if_failed); static void systemSetup(); }; diff --git a/server/main.cpp b/server/main.cpp index 1b8d1c5e..b672995f 100644 --- a/server/main.cpp +++ b/server/main.cpp @@ -206,9 +206,10 @@ int start_main(int argc,char *argv[]) { #if !defined(_WIN32) pid_t pid = getpid(); + bool kill_parent_if_failed = true; if (bDaemon) { //启动守护进程 - System::startDaemon(); + System::startDaemon(kill_parent_if_failed); } //开启崩溃捕获等 System::systemSetup(); @@ -317,7 +318,8 @@ int start_main(int argc,char *argv[]) { ErrorL << "程序启动失败,请修改配置文件中端口号后重试!" << endl; sleep(1); #if !defined(_WIN32) - if (pid != getpid()) { + if (pid != getpid() && kill_parent_if_failed) { + //杀掉守护进程 kill(pid, SIGINT); } #endif