C++ 后台进程 daemon

时间:2021-03-01 16:46:27
bool Switcher::Daemon() {
base::YamlConfig config;
if (!config_.ReadConfig(config_file_)) {
fprintf(stderr, "read config file fail.\n");
return false;
}
bool is_daemon = config_.Get<bool>(kService, "is_daemon");
if (!is_daemon) {
return true;
}
if (fork() != ) {
exit();
}
setsid();
if (fork() != ) {
exit();
} close();
close();
close();
open("/dev/null", O_RDWR);
dup();
dup(); std::string stdout_log_path;
if(config_.Get<std::string>(kService, kStdoutLogPath, &stdout_log_path)) {
string filename = stdout_log_path + "." + DateString_();
int fd = open(filename.c_str(), O_WRONLY | O_APPEND | O_CREAT, );
if (fd != -) {
// 将STDOUT, STDERROR 重定向到文件
dup2(fd, STDOUT_FILENO);
dup2(fd, STDERR_FILENO);
close(fd);
}
} return true;
}