这是一个函数,在程序中调用此函数,就可以把当前进程变为守护进程
------------------------
#include <stdio.h>
#include <signal.h>
#include <sys/param.h>
#include <errno.h>
extern int errno;
daemon_start(int ignsigcld)
{
register int childpid, fd;
if (getppid() == 1)
goto out;
#ifdef SIGTTOU
signal(SIGTTOU, SIG_IGN);
#endif
#ifdef SIGTTIN
signal(SIGTTIN, SIG_IGN);
#endif
#ifdef SIGTSTP
signal(SIGTSTP, SIG_IGN);
#endif
if ((childpid = fork()) < 0)
{
fprintf(stderr, "Can't fork first child /n");
exit(1);
}
else
if (childpid > 0)
exit(0);
if (setpgrp() == -1)
{
fprintf(stderr, "Can't change process group /n");
exit(1);
}
signal(SIGHUP, SIG_IGN);
if ((childpid = fork()) < 0)
{
fprintf(stderr, "Can't fork second child /n");
exit(1);
}
else
if (childpid > 0)
exit(0);
out:
/*
for (fd = 0;
fd <= 2;
fd++)
close(fd);
*/
errno = 0;
chdir("/");
umask(0);
if (ignsigcld)
{
signal(SIGCLD, SIG_IGN);
}
}
------------------------