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() != 0) {
exit(0);
}
setsid();
if (fork() != 0) {
exit(0);
}
close(0);
close(1);
close(2);
open("/dev/null", O_RDWR);
dup(0);
dup(0);
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, 0644);
if (fd != -1) {
// 将STDOUT, STDERROR 重定向到文件
dup2(fd, STDOUT_FILENO);
dup2(fd, STDERR_FILENO);
close(fd);
}
}
return true;
}
C++ 后台进程 daemon
转载本文章为转载内容,我们尊重原作者对文章享有的著作权。如有内容错误或侵权问题,欢迎原作者联系我们进行内容更正或删除文章。
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
Linux C编程:守护进程(Daemon进程)
1.特点: 1》生成时间较长:系统启动开始运行,系统关闭时结束; 2》通常独立于
daemon 守护进程 #include 系统日志 -
C++杀进程
源代码:#include #include #include #include #pragma comm
#include #pragma d3