blob: 7b2e19c4248128c3c7aa37cc9107d5415b25063e [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
Denis Vlasenkoaf1c8432007-03-26 13:22:35 +000026static const char *saved_pidfile;
27
28static void pidfile_delete(void)
29{
30 if (saved_pidfile)
31 unlink(saved_pidfile);
Mike Frysinger7031f622006-05-08 03:20:50 +000032}
33
Denis Vlasenkoaf1c8432007-03-26 13:22:35 +000034static 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
52static 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
62void udhcp_make_pidfile(const char *pidfile)
Mike Frysinger7031f622006-05-08 03:20:50 +000063{
64 int pid_fd;
65
Denis Vlasenkoaf1c8432007-03-26 13:22:35 +000066 /* Make sure fd 0,1,2 are open */
Denis Vlasenkoe06bed32007-01-27 22:21:12 +000067 bb_sanitize_stdio();
Mike Frysinger7031f622006-05-08 03:20:50 +000068
Denis Vlasenkoaf1c8432007-03-26 13:22:35 +000069 /* Equivalent of doing a fflush after every \n */
Mike Frysinger7031f622006-05-08 03:20:50 +000070 setlinebuf(stdout);
71
Denis Vlasenkoaf1c8432007-03-26 13:22:35 +000072 /* Create pidfile */
73 pid_fd = pidfile_acquire(pidfile);
74 pidfile_write_release(pid_fd);
Mike Frysinger7031f622006-05-08 03:20:50 +000075
Denis Vlasenko8f8f2682006-10-03 21:00:43 +000076 bb_info_msg("%s (v%s) started", applet_name, BB_VER);
Mike Frysinger7031f622006-05-08 03:20:50 +000077}