1 /* $Id: daemonize.c,v 1.13 2012/03/05 20:36:15 nanard Exp $ */
3 * http://miniupnp.free.fr/ or http://miniupnp.tuxfamily.org/
4 * (c) 2006 Thomas Bernard
5 * This software is subject to the conditions detailed
6 * in the LICENCE file provided within the distribution */
18 #include "daemonize.h"
37 /* obtain a new process group */
38 if( (pid
= setsid()) < 0)
44 /* close all descriptors */
45 for (i
=getdtablesize();i
>=0;--i
) close(i
);
47 i
= open("/dev/null", O_RDWR
); /* open stdin */
52 chdir("/"); /* chdir to /tmp ? */
64 writepidfile(const char * fname
, int pid
)
70 if(!fname
|| (strlen(fname
) == 0))
73 if( (pidfile
= open(fname
, O_WRONLY
|O_CREAT
, 0644)) < 0)
75 syslog(LOG_ERR
, "Unable to open pidfile for writing %s: %m", fname
);
79 pidstringlen
= snprintf(pidstring
, sizeof(pidstring
), "%d\n", pid
);
83 "Unable to write to pidfile %s: snprintf(): FAILED", fname
);
89 if(write(pidfile
, pidstring
, pidstringlen
) < 0)
90 syslog(LOG_ERR
, "Unable to write to pidfile %s: %m", fname
);
99 checkforrunning(const char * fname
)
105 if(!fname
|| (strlen(fname
) == 0))
108 if( (pidfile
= open(fname
, O_RDONLY
)) < 0)
111 memset(buffer
, 0, 64);
113 if(read(pidfile
, buffer
, 63))
115 if( (pid
= atol(buffer
)) > 0)