netsnmp_daemonize.c [plain text]
#include <net-snmp/net-snmp-config.h>
#undef PACKAGE_BUGREPORT
#undef PACKAGE_NAME
#undef PACKAGE_STRING
#undef PACKAGE_TARNAME
#undef PACKAGE_URL
#undef PACKAGE_VERSION
#include <config.h>
#ifdef NEED_NETSNMP_DAEMONIZE
#include <stdio.h>
#include <ctype.h>
#include <errno.h>
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#if HAVE_STDLIB_H
#include <stdlib.h>
#endif
#if TIME_WITH_SYS_TIME
# ifdef WIN32
# include <sys/timeb.h>
# else
# include <sys/time.h>
# endif
# include <time.h>
#else
# if HAVE_SYS_TIME_H
# include <sys/time.h>
# else
# include <time.h>
# endif
#endif
#include <sys/types.h>
#if HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#if HAVE_WINSOCK_H
#include <winsock.h>
#endif
#if HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#if HAVE_NET_IF_H
#include <net/if.h>
#endif
#if HAVE_SYS_SOCKIO_H
#include <sys/sockio.h>
#endif
#if HAVE_SYS_IOCTL_H
#include <sys/ioctl.h>
#endif
#ifdef HAVE_NLIST_H
#include <nlist.h>
#endif
#if HAVE_SYS_FILE_H
#include <sys/file.h>
#endif
#if HAVE_KSTAT_H
#include <kstat.h>
#endif
#if HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif
#if HAVE_SYS_SYSCTL_H
#include <sys/sysctl.h>
#endif
#if HAVE_STRING_H
#include <string.h>
#else
#include <strings.h>
#endif
#if HAVE_DMALLOC_H
#include <dmalloc.h>
#endif
#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif
#if HAVE_FCNTL_H
#include <fcntl.h>
#endif
#if defined(hpux10) || defined(hpux11)
#include <sys/pstat.h>
#endif
#if HAVE_SYS_UTSNAME_H
#include <sys/utsname.h>
#endif
#if HAVE_SYS_SYSTEMCFG_H
#include <sys/systemcfg.h>
#endif
#if HAVE_SYS_SYSTEMINFO_H
#include <sys/systeminfo.h>
#endif
#include <net-snmp/types.h>
#include <net-snmp/output_api.h>
#include <net-snmp/utilities.h>
#include <net-snmp/library/system.h>
#include <net-snmp/library/snmp_api.h>
#include <net-snmp/library/read_config.h>
#ifndef IFF_LOOPBACK
# define IFF_LOOPBACK 0
#endif
#ifdef INADDR_LOOPBACK
# define LOOPBACK INADDR_LOOPBACK
#else
# define LOOPBACK 0x7f000001
#endif
int
netsnmp_daemonize(int quit_immediately, int stderr_log)
{
int i = 0;
int saved_errno;
DEBUGMSGT(("daemonize","deamonizing...\n"));
#ifdef HAVE_WORKING_FORK
i = fork();
if (i != 0) {
saved_errno = errno;
DEBUGMSGT(("daemonize","first fork returned %d.\n", i));
if(i == -1) {
snmp_log(LOG_ERR,"first fork failed (errno %d) in "
"netsnmp_daemonize()\n", saved_errno);
return -1;
}
if (quit_immediately) {
DEBUGMSGT(("daemonize","parent exiting\n"));
exit(0);
}
} else {
#ifdef HAVE_SETSID
setsid();
#endif
if ((i = fork()) != 0) {
saved_errno = errno;
DEBUGMSGT(("daemonize","second fork returned %d.\n", i));
if(i == -1) {
snmp_log(LOG_ERR,"second fork failed (errno %d) in "
"netsnmp_daemonize()\n", saved_errno);
}
exit(0);
}
#ifndef WIN32
else {
DEBUGMSGT(("daemonize","child continuing\n"));
chdir("/");
if (!stderr_log) {
close(0);
close(1);
close(2);
open("/dev/null", O_RDWR);
dup(0);
dup(0);
}
}
#endif
}
#endif
return i;
}
#else
int netsnp_daemonize_bs;
#endif