#include <unistd.h>
#include <sys/stat.h>
#include <signal.h>
#include <iostream>
void child_handler(int signal) {
std::cout << "Child process killed." << std::endl;
}
void create_daemon() {
// 创建新进程
pid_t pid = fork();
if (pid < 0) {
std::cerr << "Failed to fork process." << std::endl;
exit(1);
}
// 父进程-退出
if (pid > 0) {
exit(0);
}
// 创建一个新 session
pid_t sid = setsid();
if (sid < 0) {
std::cerr << "Failed to create a new session." << std::endl;
exit(1);
}
// 将根目录设置为子进程的工作目录。
if (chdir("/") < 0) {
std::cerr << "Failed to change working directory." << std::endl;
exit(1);
}
// 关闭文件描述符
for (int i = 0; i < sysconf(_SC_OPEN_MAX); ++i) {
close(i);
}
return;
}
int main() {
create_daemon();
// 为子进程kill注册信号处理程序
signal(SIGTERM, child_handler);
// 创建一个新进程
pid_t pid = fork();
if (pid < 0) {
std::cerr << "Failed to fork process." << std::endl;
exit(1);
}
// In the child process
if (pid == 0) {
// Sleep for 10 seconds and then exit
std::cout << "Child process sleeping..." << std::endl;
sleep(10);
std::cout << "Child process exiting." << std::endl;
exit(0);
}
// 父进程
std::cout << "Forked child process with PID " << pid << "." << std::endl;
sleep(2); // 等待子进程运行一段时间后再杀死它
// 杀死子进程
if (kill(pid, SIGTERM) < 0) {
std::cerr << "Failed to kill child process." << std::endl;
exit(1);
}
// 等待子进程结束后退出
wait(NULL)
return 0;
}