linux c

守护进程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
pid_t pid = fork();
if (pid < 0)
{
fprintf(stderr, "fork sub process failed!!\n");
return -2;
}
else if (pid > 0)
{
fprintf(stdout, "daemon sub process %d\n", pid);
fprintf(stdout, "logfile %s\n", logfile);
exit(0); // exit this processs [parent/current]
}
else
{
setsid(); // net session and new leader.
my::close_non_std_open_fds(); // close 0,1,2 --
my::close_std_open_fds(); // close all file handle
// sub process run
ret = svc.start(workdir);
char result[2 * 1024] = {0};
sprintf(result, "xx_daemon: workdir=%s, status=%d, pid=%d!\n", workdir, ret, getpid());
syslog(LOG_INFO, result);
// wait to exit!
my::thr_sem exit_sem;
exit_sem.wait(); // no need to exit as a daemon.
svc.stop();
}

new