+/** Allocate a child callback record.
+ * @return Newly allocated callback record.
+ */
+static struct ChildRecord *alloc_crec(void)
+{
+ struct ChildRecord *crec;
+
+ if (crec_freelist)
+ {
+ crec = crec_freelist;
+ crec_freelist = crec->next;
+ }
+ else
+ {
+ crec = MyCalloc(1, sizeof(*crec));
+ }
+
+ crec->next = NULL;
+ return crec;
+}
+
+/** Release \a crec, which is after \a prev.
+ * @param[in] crec Child process callback record to release.
+ */
+static void release_crec(struct ChildRecord *crec)
+{
+ memset(crec, 0, sizeof(*crec));
+ crec->next = crec_freelist;
+ crec_freelist = crec;
+}
+
+/** Register a function to be called when a child process terminates.
+ * @param[in] child Child process ID.
+ * @param[in] call Function to call when process \a child terminates.
+ * @param[in] datum Additional data parameter to pass to \a call.
+ */
+void register_child(pid_t child, SigChldCallBack call, void *datum)
+{
+ struct ChildRecord *crec;
+
+ crec = alloc_crec();
+ /* Link into #children list. */
+ crec->next = children;
+ children = crec;
+ /* Fill in user fields. */
+ crec->call = call;
+ crec->datum = datum;
+ crec->cpid = child;
+}
+
+/** Unregister all callbacks for a child process, optionally calling
+ * them first.
+ * @param[in] child Child process ID to unregister.
+ * @param[in] do_call If non-zero, make the callbacks.
+ * @param[in] status If \a do_call is non-zero, the child's exit status.
+ */
+static void do_unregister_child(pid_t child, int do_call, int status)
+{
+ struct ChildRecord *crec = children;
+ struct ChildRecord *prev = NULL;
+
+ while (crec != NULL)
+ {
+ if (crec->cpid == child)
+ {
+ if (do_call)
+ crec->call(child, crec->datum, status);
+
+ if (prev)
+ prev->next = crec->next;
+ else
+ children = crec->next;
+
+ release_crec(crec);
+ }
+ else
+ prev = crec;
+ crec = prev ? prev->next : children;
+ }
+}
+
+/** Unregister all callbacks for a child process.
+ * @param[in] child Child process ID to unregister.
+ */
+void unregister_child(pid_t child)
+{
+ do_unregister_child(child, 0, 0);
+}
+
+/** Signal handler for SIGCHLD.
+ * @param[in] ev Signal event descriptor.
+ */
+static void sigchld_callback(struct Event *ev)
+{
+ pid_t cpid;
+ int status;
+
+ ++SignalCounter.chld;
+ do {
+ cpid = waitpid(-1, &status, WNOHANG);
+ if (cpid > 0)
+ do_unregister_child(cpid, 1, status);
+ } while (cpid > 0);
+}
+