您的位置:首页 > 运维架构 > Linux

How to Daemonize in Linux

2012-08-02 00:04 447 查看
转自http://www.itp.uzh.ch/~dpotter/howto/daemonize

简单易懂的daemonize实现代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>

#define EXIT_SUCCESS 0
#define EXIT_FAILURE 1

static void daemonize(void)
{
pid_t pid, sid;

/* already a daemon */
if (getppid() == 1) {
return;
}

/* Fork off the parent process */
pid = fork();
if (pid < 0) {
exit(EXIT_FAILURE);
}
/* If we got a good PID, then we can exit the parent process. */
if (pid > 0) {
exit(EXIT_SUCCESS);
}

/* At this point we are executing as the child process */

/* Change the file mode mask */
umask(0);

/* Create a new SID for the child process */
sid = setsid();
if (sid < 0) {
exit(EXIT_FAILURE);
}

/* Change the current working directory.  This prevents the current
*        directory from being locked; hence not being able to remove it. */
if ((chdir("/")) < 0) {
exit(EXIT_FAILURE);
}

/* Redirect standard files to /dev/null */
freopen("/dev/null", "r", stdin);
freopen("/dev/null", "w", stdout);
freopen("/dev/null", "w", stderr);
}

int main(int argc, char **argv)
{
daemonize();

/* Now we are a daemon -- do the work for which we were paid */

while (1) {
sleep(1);
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: