2 dropin.c -- a set of drop-in replacements for libc functions
3 Copyright (C) 2000-2005 Ivo Timmermans,
4 2000-2016 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.
27 Replacement for the daemon() function.
29 The daemon() function is for programs wishing to detach themselves
30 from the controlling terminal and run in the background as system
33 Unless the argument nochdir is non-zero, daemon() changes the
34 current working directory to the root (``/'').
36 Unless the argument noclose is non-zero, daemon() will redirect
37 standard input, standard output and standard error to /dev/null.
39 int daemon(int nochdir, int noclose) {
46 /* Check if forking failed */
52 /* If we are the parent, terminate */
56 /* Detach by becoming the new process group leader */
62 /* Change working directory to the root (to avoid keeping mount
68 /* Redirect stdin/out/err to /dev/null */
70 fd = open("/dev/null", O_RDWR);
73 perror("opening /dev/null");
90 int asprintf(char **buf, const char *fmt, ...) {
94 result = vasprintf(buf, fmt, ap);
99 int vasprintf(char **buf, const char *fmt, va_list ap) {
108 status = vsnprintf(*buf, len, fmt, aq);
112 *buf = xrealloc(*buf, status + 1);
114 if(status > len - 1) {
117 status = vsnprintf(*buf, len, fmt, aq);
125 #ifndef HAVE_GETTIMEOFDAY
126 int gettimeofday(struct timeval *tv, void *tz) {
129 GetSystemTimeAsFileTime(&ft);
130 uint64_t lt = (uint64_t)ft.dwLowDateTime | ((uint64_t)ft.dwHighDateTime << 32);
131 lt -= 116444736000000000ULL;
132 tv->tv_sec = lt / 10000000;
133 tv->tv_usec = (lt / 10) % 1000000;
135 #warning No high resolution time source!
136 tv->tv_sec = time(NULL);
143 #ifndef HAVE_NANOSLEEP
144 int nanosleep(const struct timespec *req, struct timespec *rem) {
145 struct timeval tv = {req->tv_sec, req->tv_nsec / 1000};
146 return select(0, NULL, NULL, NULL, &tv);