2 dropin.c -- a set of drop-in replacements for libc functions
3 Copyright (C) 2000-2003 Ivo Timmermans <ivo@o2w.nl>,
4 2000-2003 Guus Sliepen <guus@sliepen.eu.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
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 $Id: dropin.c,v 1.1.2.18 2003/07/29 22:59:00 guus Exp $
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)
49 /* Check if forking failed */
55 /* 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");
92 #ifndef HAVE_GET_CURRENT_DIR_NAME
94 Replacement for the GNU get_current_dir_name function:
96 get_current_dir_name will malloc(3) an array big enough to hold the
97 current directory name. If the environment variable PWD is set, and
98 its value is correct, then that value will be returned.
100 char *get_current_dir_name(void)
106 /* Start with 100 bytes. If this turns out to be insufficient to
107 contain the working directory, double the size. */
111 errno = 0; /* Success */
112 r = getcwd(buf, size);
114 /* getcwd returns NULL and sets errno to ERANGE if the bufferspace
115 is insufficient to contain the entire working directory. */
116 while(r == NULL && errno == ERANGE) {
118 size <<= 1; /* double the size */
120 r = getcwd(buf, size);
127 #ifndef HAVE_ASPRINTF
128 int asprintf(char **buf, const char *fmt, ...)
138 status = vsnprintf(*buf, len, fmt, ap);
142 *buf = xrealloc(*buf, status + 1);
144 if(status > len - 1) {
147 status = vsnprintf(*buf, len, fmt, ap);
155 #ifndef HAVE_GETTIMEOFDAY
156 int gettimeofday(struct timeval *tv, void *tz) {
157 tv->tv_sec = time(NULL);
164 #include <openssl/rand.h>
166 long int random(void) {
169 RAND_pseudo_bytes((unsigned char *)&x, sizeof(x));