4c18e5d5134bb8d150ff088f7331de3205698a0b
[oweals/busybox.git] / networking / udhcp / common.c
1 /* vi: set sw=4 ts=4: */
2 /* common.c
3  *
4  * Functions for debugging and logging as well as some other
5  * simple helper functions.
6  *
7  * Russ Dill <Russ.Dill@asu.edu> 2001-2003
8  * Rewritten by Vladimir Oleynik <dzo@simtreas.ru> (C) 2003
9  *
10  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
11  */
12
13 #include <syslog.h>
14
15 #include "common.h"
16
17
18 long uptime(void)
19 {
20         struct sysinfo info;
21         sysinfo(&info);
22         return info.uptime;
23 }
24
25 /*
26  * This function makes sure our first socket calls
27  * aren't going to fd 1 (printf badness...) and are
28  * not later closed by daemon()
29  */
30 static inline void sanitize_fds(void)
31 {
32         int fd = open(bb_dev_null, O_RDWR, 0);
33         if (fd < 0)
34                 return;
35         while (fd < 3)
36                 fd = dup(fd);
37         close(fd);
38 }
39
40
41 void udhcp_background(const char *pidfile)
42 {
43 #ifdef __uClinux__
44         bb_error_msg("cannot background in uclinux (yet)");
45 #else /* __uClinux__ */
46         int pid_fd;
47
48         /* hold lock during fork. */
49         pid_fd = pidfile_acquire(pidfile);
50         setsid();
51         xdaemon(0, 0);
52         logmode &= ~LOGMODE_STDIO;
53         pidfile_write_release(pid_fd);
54 #endif /* __uClinux__ */
55 }
56
57 void udhcp_start_log_and_pid(const char *pidfile)
58 {
59         int pid_fd;
60
61         /* Make sure our syslog fd isn't overwritten */
62         sanitize_fds();
63
64         /* do some other misc startup stuff while we are here to save bytes */
65         pid_fd = pidfile_acquire(pidfile);
66         pidfile_write_release(pid_fd);
67
68         /* equivelent of doing a fflush after every \n */
69         setlinebuf(stdout);
70
71         if (ENABLE_FEATURE_UDHCP_SYSLOG) {
72                 openlog(applet_name, LOG_PID, LOG_LOCAL0);
73                 logmode |= LOGMODE_SYSLOG;
74         }
75
76         bb_info_msg("%s (v%s) started", applet_name, BB_VER);
77 }