2 dropin.c -- a set of drop-in replacements for libc functions
3 Copyright (C) 2000-2005 Ivo Timmermans,
4 2000-2018 Guus Sliepen <guus@tinc-vpn.org>
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License along
17 with this program; if not, write to the Free Software Foundation, Inc.,
18 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
29 Replacement for the daemon() function.
31 The daemon() function is for programs wishing to detach themselves
32 from the controlling terminal and run in the background as system
35 Unless the argument nochdir is non-zero, daemon() changes the
36 current working directory to the root (``/'').
38 Unless the argument noclose is non-zero, daemon() will redirect
39 standard input, standard output and standard error to /dev/null.
41 int daemon(int nochdir, int noclose) {
48 /* Check if forking failed */
54 /* If we are the parent, terminate */
59 /* Detach by becoming the new process group leader */
65 /* Change working directory to the root (to avoid keeping mount
71 /* Redirect stdin/out/err to /dev/null */
73 fd = open("/dev/null", O_RDWR);
76 perror("opening /dev/null");
95 int asprintf(char **buf, const char *fmt, ...) {
99 result = vasprintf(buf, fmt, ap);
104 int vasprintf(char **buf, const char *fmt, va_list ap) {
113 status = vsnprintf(*buf, len, fmt, aq);
117 *buf = xrealloc(*buf, status + 1);
120 if(status > len - 1) {
123 status = vsnprintf(*buf, len, fmt, aq);
131 #ifndef HAVE_GETTIMEOFDAY
132 int gettimeofday(struct timeval *tv, void *tz) {
135 GetSystemTimeAsFileTime(&ft);
136 uint64_t lt = (uint64_t)ft.dwLowDateTime | ((uint64_t)ft.dwHighDateTime << 32);
137 lt -= 116444736000000000ULL;
138 tv->tv_sec = lt / 10000000;
139 tv->tv_usec = (lt / 10) % 1000000;
141 #warning No high resolution time source!
142 tv->tv_sec = time(NULL);
149 #ifndef HAVE_NANOSLEEP
150 int nanosleep(const struct timespec *req, struct timespec *rem) {
152 struct timeval tv = {req->tv_sec, req->tv_nsec / 1000};
153 return select(0, NULL, NULL, NULL, &tv);