#!/bin/sh

# Logfile as first parameter is required
logfile="$1"
shift

# Ctrl-C should only kill strace, not the rest of the script
trap '' INT

# Create one logfiles per pid, then consolidate them into one,
# sorted by timestamp and containing the pid as 2nd column
strace -tt -ff -o "$logfile" "$@"
{
  for file in "$logfile".*; do
    pid=$(printf "%-5u" "${file##$logfile.}")
    cat "$file" | sed -r "s/^([0-9]+ +)?([^ ]+)(.*)/\2 $pid\3/"
  done
} | sort > "$logfile"

# Clean up temporary logfiles
rm "$logfile".*
