blob: 3e916f42286add69b472838ade134d726892f4a9 [file] [log] [blame]
Mike Frysinger7031f622006-05-08 03:20:50 +00001/* 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
Denis Vlasenko3538b9a2006-09-06 18:36:50 +000013#include <syslog.h>
Mike Frysinger7031f622006-05-08 03:20:50 +000014
15#include "common.h"
Mike Frysinger7031f622006-05-08 03:20:50 +000016
17
Mike Frysinger7031f622006-05-08 03:20:50 +000018long uptime(void)
19{
20 struct sysinfo info;
21 sysinfo(&info);
22 return info.uptime;
23}
24
Mike Frysinger7031f622006-05-08 03:20:50 +000025/*
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 */
30static inline void sanitize_fds(void)
31{
Denis Vlasenko61126ab2006-11-18 22:03:26 +000032 int fd = xopen(bb_dev_null, O_RDWR);
Denis Vlasenko3538b9a2006-09-06 18:36:50 +000033 while (fd < 3)
34 fd = dup(fd);
35 close(fd);
Mike Frysinger7031f622006-05-08 03:20:50 +000036}
37
38
Rob Landley3f785612006-05-28 01:06:36 +000039void udhcp_background(const char *pidfile)
Mike Frysinger7031f622006-05-08 03:20:50 +000040{
41#ifdef __uClinux__
Denis Vlasenkoe1a0d482006-10-20 13:28:22 +000042 bb_error_msg("cannot background in uclinux (yet)");
Mike Frysinger7031f622006-05-08 03:20:50 +000043#else /* __uClinux__ */
44 int pid_fd;
45
46 /* hold lock during fork. */
47 pid_fd = pidfile_acquire(pidfile);
Denis Vlasenko3538b9a2006-09-06 18:36:50 +000048 setsid();
Denis Vlasenko27af5a02006-09-03 12:21:59 +000049 xdaemon(0, 0);
Denis Vlasenko3538b9a2006-09-06 18:36:50 +000050 logmode &= ~LOGMODE_STDIO;
Mike Frysinger7031f622006-05-08 03:20:50 +000051 pidfile_write_release(pid_fd);
52#endif /* __uClinux__ */
53}
54
Denis Vlasenko239369b2006-09-07 17:05:44 +000055void udhcp_start_log_and_pid(const char *pidfile)
Mike Frysinger7031f622006-05-08 03:20:50 +000056{
57 int pid_fd;
58
59 /* Make sure our syslog fd isn't overwritten */
60 sanitize_fds();
61
62 /* do some other misc startup stuff while we are here to save bytes */
63 pid_fd = pidfile_acquire(pidfile);
64 pidfile_write_release(pid_fd);
65
66 /* equivelent of doing a fflush after every \n */
67 setlinebuf(stdout);
68
Denis Vlasenko3538b9a2006-09-06 18:36:50 +000069 if (ENABLE_FEATURE_UDHCP_SYSLOG) {
Denis Vlasenko8f8f2682006-10-03 21:00:43 +000070 openlog(applet_name, LOG_PID, LOG_LOCAL0);
Denis Vlasenko3538b9a2006-09-06 18:36:50 +000071 logmode |= LOGMODE_SYSLOG;
72 }
Mike Frysinger7031f622006-05-08 03:20:50 +000073
Denis Vlasenko8f8f2682006-10-03 21:00:43 +000074 bb_info_msg("%s (v%s) started", applet_name, BB_VER);
Mike Frysinger7031f622006-05-08 03:20:50 +000075}