OSDN Git Service

1ae65f75085c9dee64b103a59fa238811f75b225
[android-x86/external-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 <fcntl.h>
14 #include <unistd.h>
15 #include <errno.h>
16 #include <string.h>
17 #include <stdlib.h>
18 #include <signal.h>
19 #include <paths.h>
20 #include <sys/socket.h>
21 #include <stdarg.h>
22 #include <syslog.h>
23
24 #include "common.h"
25 #include "pidfile.h"
26
27
28 static int daemonized;
29
30 long uptime(void)
31 {
32         struct sysinfo info;
33         sysinfo(&info);
34         return info.uptime;
35 }
36
37 /*
38  * This function makes sure our first socket calls
39  * aren't going to fd 1 (printf badness...) and are
40  * not later closed by daemon()
41  */
42 static inline void sanitize_fds(void)
43 {
44         int fd = open(bb_dev_null, O_RDWR, 0);
45         if (fd < 0)
46                 return;
47         while (fd < 3)
48                 fd = dup(fd);
49         close(fd);
50 }
51
52
53 void udhcp_background(const char *pidfile)
54 {
55 #ifdef __uClinux__
56         bb_error_msg("Cannot background in uclinux (yet)");
57 #else /* __uClinux__ */
58         int pid_fd;
59
60         /* hold lock during fork. */
61         pid_fd = pidfile_acquire(pidfile);
62         setsid();
63         xdaemon(0, 0);
64         daemonized++;
65         logmode &= ~LOGMODE_STDIO;
66         pidfile_write_release(pid_fd);
67 #endif /* __uClinux__ */
68 }
69
70 void udhcp_start_log_and_pid(const char *client_server, const char *pidfile)
71 {
72         int pid_fd;
73
74         /* Make sure our syslog fd isn't overwritten */
75         sanitize_fds();
76
77         /* do some other misc startup stuff while we are here to save bytes */
78         pid_fd = pidfile_acquire(pidfile);
79         pidfile_write_release(pid_fd);
80
81         /* equivelent of doing a fflush after every \n */
82         setlinebuf(stdout);
83
84         if (ENABLE_FEATURE_UDHCP_SYSLOG) {
85                 openlog(client_server, LOG_PID, LOG_LOCAL0);
86                 logmode |= LOGMODE_SYSLOG;
87         }
88
89         bb_info_msg("%s (v%s) started", client_server, BB_VER);
90 }