- 论坛徽章:
- 0
|
if(!setToForeground )
{
#ifdef LINUX
daemon(0, ucDebug);
#elif defined UCLINUX
daemonize(ucDebug, argc, argv);
#endif
}
---------------------------------------------------------------------
/*For uClinux doesn't support daemon() function, so we need implement it by ourself.*/
void daemonize (unsigned char ucDebug, int argc, char **argv)
{
int iRet = 0;
int fd = -1;
if (1 == getppid ()) /* already a daemon */
{
setsid (); /* set new process group */
if (0x00 == ucDebug)
{
/*Close all the file description.*/
for (iRet = getdtablesize (); 0 <= iRet; --iRet)
{
fd = iRet;
close(fd);
}
fd = open("/dev/null", O_RDWR); /*Redirect Standard input [0] to /dev/null */
dup (fd); /*Redirect Standard output [1] to /dev/null */
dup (fd); /*Redirect Standard error [2] to /dev/null */
}
umask (027); /* set newly created file mode mask */
chdir("/"); // change running directory
return ;
}
else
{
iRet = vfork ();
if (0 > iRet) _exit (1); /* fork error */
if (0 < iRet) _exit (0); /* parent exit */
/*Child process(daemon) continue and fork again.*/
iRet = vfork ();
if (0 > iRet) _exit (1); /* fork error */
if (0 < iRet) _exit (0); /* parent exists */
/* Parent exit, so child process parent pid should be init process(pid is 1) */
execv (argv[0], argv); /*Run the pograme again.*/
_exit (1); /*If execv() returned, then something error happend.*/
}
} |
|