From 1bc522424f6bb21842366ccd11953136436b684b Mon Sep 17 00:00:00 2001
From: Rob Landley <rob@landley.net>
Date: Wed, 21 May 2014 07:24:16 -0500
Subject: Add generic_signal() handler, which sets toys.signal and writes byte
 to toys.signalfd if set.

---
 lib/lib.c | 12 ++++++++++++
 lib/lib.h |  1 +
 main.c    |  1 +
 toys.h    |  3 +++
 4 files changed, 17 insertions(+)

diff --git a/lib/lib.c b/lib/lib.c
index 1ab80351..bbe8f33c 100644
--- a/lib/lib.c
+++ b/lib/lib.c
@@ -614,12 +614,24 @@ static struct signame signames[] = {
 // not in posix: SIGNIFY(STKFLT), SIGNIFY(WINCH), SIGNIFY(IO), SIGNIFY(PWR)
 // obsolete: SIGNIFY(PROF) SIGNIFY(POLL)
 
+// Handler that sets toys.signal, and writes to toys.signalfd if set
+void generic_signal(int sig)
+{
+  if (toys.signalfd) {
+    char c = sig;
+
+    writeall(toys.signalfd, &c, 1);
+  }
+  toys.signal = sig;
+}
+
 // Install the same handler on every signal that defaults to killing the process
 void sigatexit(void *handler)
 {
   int i;
   for (i=0; signames[i].num != SIGCHLD; i++) signal(signames[i].num, handler);
 }
+
 // Convert name to signal number.  If name == NULL print names.
 int sig_to_num(char *pidstr)
 {
diff --git a/lib/lib.h b/lib/lib.h
index f8fcd8fe..097e67d8 100644
--- a/lib/lib.h
+++ b/lib/lib.h
@@ -174,6 +174,7 @@ struct mtab_list *xgetmountlist(char *path);
 
 // signal
 
+void generic_signal(int signal);
 void sigatexit(void *handler);
 int sig_to_num(char *pidstr);
 char *num_to_sig(int sig);
diff --git a/main.c b/main.c
index 92ec89fa..38f6d1ad 100644
--- a/main.c
+++ b/main.c
@@ -80,6 +80,7 @@ static void toy_singleinit(struct toy_list *which, char *argv[])
   }
   toys.old_umask = umask(0);
   if (!(which->flags & TOYFLAG_UMASK)) umask(toys.old_umask);
+  toys.signalfd--;
 }
 
 // Setup toybox global state for this command.
diff --git a/toys.h b/toys.h
index c59c3c51..6666cfbf 100644
--- a/toys.h
+++ b/toys.h
@@ -23,6 +23,7 @@
 #include <regex.h>
 #include <sched.h>
 #include <setjmp.h>
+#include <signal.h>
 #include <stdarg.h>
 #include <stddef.h>
 #include <stdint.h>
@@ -125,6 +126,8 @@ extern struct toy_context {
   int exithelp;            // Should error_exit print a usage message first?
   int old_umask;           // Old umask preserved by TOYFLAG_UMASK
   int toycount;            // Total number of commands in this build
+  int signal;              // generic_signal() records what signal it saw here
+  int signalfd;            // and writes signal to this fd, if set
 
   // This is at the end so toy_init() doesn't zero it.
   jmp_buf *rebound;        // longjmp here instead of exit when do_rebound set
-- 
cgit v1.2.3