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.
29 #include "sighandlers.h"
33 * Initialize process structure.
36 Proc_InitStruct (PROC_STAT *proc)
44 * Fork a child process.
47 Proc_Fork(PROC_STAT *proc, int *pipefds, void (*cbfunc)(int, short), int timeout)
50 #ifndef HAVE_ARC4RANDOM
55 assert(pipefds != NULL);
56 assert(cbfunc != NULL);
58 if (pipe(pipefds) != 0) {
59 Log(LOG_ALERT, "Can't create output pipe for child process: %s!",
64 #ifndef HAVE_ARC4RANDOM
65 seed = (unsigned int)rand();
71 Log(LOG_CRIT, "Can't fork child process: %s!", strerror(errno));
76 /* New child process: */
77 #ifdef HAVE_ARC4RANDOM_STIR
80 #ifndef HAVE_ARC4RANDOM
81 srand(seed ^ (unsigned int)time(NULL) ^ getpid());
84 signal(SIGTERM, Proc_GenericSignalHandler);
85 signal(SIGALRM, Proc_GenericSignalHandler);
91 /* Old parent process: */
94 if (!io_setnonblock(pipefds[0])
95 || !io_event_create(pipefds[0], IO_WANTREAD, cbfunc)) {
96 Log(LOG_CRIT, "Can't register callback for child process: %s!",
103 proc->pipe_fd = pipefds[0];
108 * Generic signal handler for forked child processes.
111 Proc_GenericSignalHandler(int Signal)
116 Log_Subprocess(LOG_DEBUG, "Child got TERM signal, exiting.");
121 Log_Subprocess(LOG_DEBUG, "Child got ALARM signal, exiting.");
128 * Read bytes from a pipe of a forked child process.
129 * In addition, this function makes sure that the child process is ignored
130 * after all data has been read or a fatal error occurred.
133 Proc_Read(PROC_STAT *proc, void *buffer, size_t buflen)
135 ssize_t bytes_read = 0;
137 assert(buffer != NULL);
140 bytes_read = read(proc->pipe_fd, buffer, buflen);
141 if (bytes_read < 0) {
144 Log(LOG_CRIT, "Can't read from child process %ld: %s",
145 proc->pid, strerror(errno));
148 } else if (bytes_read == 0) {
150 LogDebug("Child process %ld: EOF reached, closing pipe.",
154 return (size_t)bytes_read;
158 * Close pipe to a forked child process.
161 Proc_Close(PROC_STAT *proc)
163 /* Close socket, if it exists */
164 if (proc->pipe_fd >= 0)
165 io_close(proc->pipe_fd);
167 Proc_InitStruct(proc);