子进程重启失败时,不应通知守护进程退出,确保子进程重启成功

This commit is contained in:
xiongziliang 2022-04-09 21:02:54 +08:00
parent c334dcfd38
commit e065b1dfba
3 changed files with 18 additions and 13 deletions

View File

@ -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
}

View File

@ -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();
};

View File

@ -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