7b2e19c4248128c3c7aa37cc9107d5415b25063e
[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 static const char *saved_pidfile;
27
28 static void pidfile_delete(void)
29 {
30         if (saved_pidfile)
31                 unlink(saved_pidfile);
32 }
33
34 static int pidfile_acquire(const char *pidfile)
35 {
36         int pid_fd;
37         if (!pidfile) return -1;
38
39         pid_fd = open(pidfile, O_CREAT|O_WRONLY|O_TRUNC, 0644);
40         if (pid_fd < 0) {
41                 bb_perror_msg("cannot open pidfile %s", pidfile);
42         } else {
43                 /* lockf(pid_fd, F_LOCK, 0); */
44                 if (!saved_pidfile)
45                         atexit(pidfile_delete);
46                 saved_pidfile = pidfile;
47         }
48
49         return pid_fd;
50 }
51
52 static void pidfile_write_release(int pid_fd)
53 {
54         if (pid_fd < 0) return;
55
56         fdprintf(pid_fd, "%d\n", getpid());
57         /* lockf(pid_fd, F_UNLCK, 0); */
58         close(pid_fd);
59 }
60
61
62 void udhcp_make_pidfile(const char *pidfile)
63 {
64         int pid_fd;
65
66         /* Make sure fd 0,1,2 are open */
67         bb_sanitize_stdio();
68
69         /* Equivalent of doing a fflush after every \n */
70         setlinebuf(stdout);
71
72         /* Create pidfile */
73         pid_fd = pidfile_acquire(pidfile);
74         pidfile_write_release(pid_fd);
75
76         bb_info_msg("%s (v%s) started", applet_name, BB_VER);
77 }