2 * ngIRCd -- The Next Generation IRC Daemon
3 * Copyright (c)2001-2011 Alexander Barton (alex@barton.de) and Contributors.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 * Please read the file COPYING, README and AUTHORS for more information.
32 #include "sighandlers.h"
36 * Initialize process structure.
39 Proc_InitStruct (PROC_STAT *proc)
47 * Fork a child process.
50 Proc_Fork(PROC_STAT *proc, int *pipefds, void (*cbfunc)(int, short), int timeout)
53 #ifndef HAVE_ARC4RANDOM
58 assert(pipefds != NULL);
59 assert(cbfunc != NULL);
61 if (pipe(pipefds) != 0) {
62 Log(LOG_ALERT, "Can't create output pipe for child process: %s!",
67 #ifndef HAVE_ARC4RANDOM
68 seed = (unsigned int)rand();
74 Log(LOG_CRIT, "Can't fork child process: %s!", strerror(errno));
79 /* New child process: */
80 #ifdef HAVE_ARC4RANDOM_STIR
83 #ifndef HAVE_ARC4RANDOM
84 srand(seed ^ (unsigned int)time(NULL) ^ getpid());
87 signal(SIGTERM, Proc_GenericSignalHandler);
88 signal(SIGALRM, Proc_GenericSignalHandler);
94 /* Old parent process: */
97 if (!io_setnonblock(pipefds[0])
98 || !io_event_create(pipefds[0], IO_WANTREAD, cbfunc)) {
99 Log(LOG_CRIT, "Can't register callback for child process: %s!",
106 proc->pipe_fd = pipefds[0];
111 * Generic signal handler for forked child processes.
114 Proc_GenericSignalHandler(int Signal)
119 Log_Subprocess(LOG_DEBUG, "Child got TERM signal, exiting.");
124 Log_Subprocess(LOG_DEBUG, "Child got ALARM signal, exiting.");
131 * Read bytes from a pipe of a forked child process.
132 * In addition, this function makes sure that the child process is ignored
133 * after all data has been read or a fatal error occurred.
136 Proc_Read(PROC_STAT *proc, void *buffer, size_t buflen)
138 ssize_t bytes_read = 0;
140 assert(buffer != NULL);
143 bytes_read = read(proc->pipe_fd, buffer, buflen);
144 if (bytes_read < 0) {
147 Log(LOG_CRIT, "Can't read from child process %ld: %s",
148 proc->pid, strerror(errno));
151 } else if (bytes_read == 0) {
153 LogDebug("Child process %ld: EOF reached, closing pipe.",
157 return (size_t)bytes_read;
161 * Close pipe to a forked child process.
164 Proc_Close(PROC_STAT *proc)
166 /* Close socket, if it exists */
167 if (proc->pipe_fd >= 0)
168 io_close(proc->pipe_fd);
170 Proc_InitStruct(proc);