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 */
57 /* Detach by becoming the new process group leader */
63 /* Change working directory to the root (to avoid keeping mount
69 /* Redirect stdin/out/err to /dev/null */
71 fd = open("/dev/null", O_RDWR);
74 perror("opening /dev/null");
91 int asprintf(char **buf, const char *fmt, ...) {
95 result = vasprintf(buf, fmt, ap);
100 int vasprintf(char **buf, const char *fmt, va_list ap) {
109 status = vsnprintf(*buf, len, fmt, aq);
113 *buf = xrealloc(*buf, status + 1);
116 if(status > len - 1) {
119 status = vsnprintf(*buf, len, fmt, aq);
127 #ifndef HAVE_GETTIMEOFDAY
128 int gettimeofday(struct timeval *tv, void *tz) {
131 GetSystemTimeAsFileTime(&ft);
132 uint64_t lt = (uint64_t)ft.dwLowDateTime | ((uint64_t)ft.dwHighDateTime << 32);
133 lt -= 116444736000000000ULL;
134 tv->tv_sec = lt / 10000000;
135 tv->tv_usec = (lt / 10) % 1000000;
137 #warning No high resolution time source!
138 tv->tv_sec = time(NULL);
145 #ifndef HAVE_NANOSLEEP
146 int nanosleep(const struct timespec *req, struct timespec *rem) {
147 struct timeval tv = {req->tv_sec, req->tv_nsec / 1000};
148 return select(0, NULL, NULL, NULL, &tv);