Unbuffer log output

* Force-flush log output so we don't lose log output in certain error cases.
* Slow down exit paths: add sleep to die(), wait until last moment to
  kill child processes (including the awk log output filter)

Change-Id: I1620fd33b89b237d9c2bb6206f3de2c81719f676
diff --git a/stack.sh b/stack.sh
index 22a418f..c951997 100755
--- a/stack.sh
+++ b/stack.sh
@@ -522,7 +522,7 @@
     exec 3>&1
     if [[ "$VERBOSE" == "True" ]]; then
         # Redirect stdout/stderr to tee to write the log file
-        exec 1> >( awk '
+        exec 1> >( awk -v logfile=${LOGFILE} '
                 /((set \+o$)|xtrace)/ { next }
                 {
                     cmd ="date +\"%Y-%m-%d %H:%M:%S.%3N | \""
@@ -530,8 +530,9 @@
                     close("date +\"%Y-%m-%d %H:%M:%S.%3N | \"")
                     sub(/^/, now)
                     print
-                    fflush()
-                }' | tee "${LOGFILE}" ) 2>&1
+                    print > logfile
+                    fflush("")
+                }' ) 2>&1
         # Set up a second fd for output
         exec 6> >( tee "${SUMFILE}" )
     else
@@ -579,21 +580,24 @@
 # -----------------------
 
 # Kill background processes on exit
-trap clean EXIT
-clean() {
+trap exit_trap EXIT
+function exit_trap {
     local r=$?
-    kill >/dev/null 2>&1 $(jobs -p)
+    echo "exit_trap called, cleaning up child processes"
+    kill 2>&1 $(jobs -p)
     exit $r
 }
 
-
 # Exit on any errors so that errors don't compound
-trap failed ERR
-failed() {
+trap err_trap ERR
+function err_trap {
     local r=$?
-    kill >/dev/null 2>&1 $(jobs -p)
     set +o xtrace
-    [ -n "$LOGFILE" ] && echo "${0##*/} failed: full log in $LOGFILE"
+    if [[ -n "$LOGFILE" ]]; then
+        echo "${0##*/} failed: full log in $LOGFILE"
+    else
+        echo "${0##*/} failed"
+    fi
     exit $r
 }