From: =?utf-8?b?SmFuIE1vasW+w63FoQ==?= <jan.mojzis@gmail.com>
Date: Thu, 30 Dec 2021 07:54:34 +0100
Subject: add killafter

Forwarded: not-needed
---
 cpucycles/do   |  2 +-
 do             |  7 +++++++
 killafter/do   | 30 ++++++++++++++++++++++++++++++
 killafter/pg.c | 47 +++++++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 85 insertions(+), 1 deletion(-)
 create mode 100644 killafter/do
 create mode 100644 killafter/pg.c

diff --git a/cpucycles/do b/cpucycles/do
index efc063d..a548546 100755
--- a/cpucycles/do
+++ b/cpucycles/do
@@ -82,7 +82,7 @@ okabi | (
             cp $n.h cpucycles-impl.h || continue
             $c -c cpucycles-impl.c || continue
             $c -o test test.c cpucycles-impl.o || continue
-            ./test || continue
+            killafter 60 ./test || continue
             echo "=== `date` === Success. Using $n.c." >&2
             mkdir -p lib/$abi
             mv cpucycles-impl.o lib/$abi/cpucycles.o
diff --git a/do b/do
index 7a1118a..d36f293 100755
--- a/do
+++ b/do
@@ -95,6 +95,13 @@ cp -pr inttypes/* "$work"
 ( cd "$work" && sh do )
 cp -pr "$work"/include/* "$include"
 
+echo "=== `date` === building killafter"
+rm -rf "$work"
+mkdir -p "$work"
+cp -pr killafter/* "$work"
+( cd "$work" && sh do )
+cp -p "$work"/bin/* "$bin"
+
 echo "=== `date` === building cpucycles"
 rm -rf "$work"
 mkdir -p "$work"
diff --git a/killafter/do b/killafter/do
new file mode 100644
index 0000000..ce77e15
--- /dev/null
+++ b/killafter/do
@@ -0,0 +1,30 @@
+#!/bin/sh -e
+
+mkdir bin
+
+(
+  echo pg
+) | (
+  while read n
+  do
+    okabi | (
+      while read abi
+      do
+        okc-$abi | (
+          while read c
+          do
+            echo "=== `date` === Trying $n.c with $c..." >&2
+            rm -f killafter.c
+	    cp $n.c killafter.c || continue
+            $c -o killafter killafter.c || continue
+	    cp killafter bin/killafter
+            exit 0
+          done
+          exit 111
+        ) && exit 0
+      done
+      exit 111
+    ) && exit 0
+  done
+  exit 111
+)
diff --git a/killafter/pg.c b/killafter/pg.c
new file mode 100644
index 0000000..41b59c0
--- /dev/null
+++ b/killafter/pg.c
@@ -0,0 +1,47 @@
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <signal.h>
+
+pid_t f;
+
+void timeout(int s)
+{
+  killpg(f,SIGTERM);
+  kill(getpid(),SIGALRM);
+  _exit(111);
+}
+
+int main(int argc,char **argv)
+{
+  struct sigaction sa;
+  int seconds;
+  int w;
+
+  if (!*argv) return 100;
+
+  if (!*++argv) return 100;
+  seconds = atoi(*argv);
+
+  if (!*++argv) return 100;
+
+  f = fork();
+  if (f == -1) return 111;
+
+  if (f == 0) {
+    setpgid(0,0);
+    execvp(*argv,argv);
+    return 111;
+  }
+
+  sa.sa_handler = timeout;
+  sigemptyset(&sa.sa_mask);
+  sa.sa_flags = SA_RESETHAND | SA_NODEFER;
+  sigaction(SIGALRM,&sa,0);
+  alarm(seconds);
+
+  while (wait(&w) != f) ;
+  if (WIFEXITED(w)) return WEXITSTATUS(w);
+  return 111;
+}
