Skip to content

Instantly share code, notes, and snippets.

@psobot
Last active October 31, 2022 12:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save psobot/6814658 to your computer and use it in GitHub Desktop.
Save psobot/6814658 to your computer and use it in GitHub Desktop.
Dump a stack trace of a Go process without stderr attached. This is a super dirty hack, but it uses strace, pgrep and python to send QUIT to a Golang process, intercept its system calls to stderr, and format them nicely for humans. Tested on Ubuntu with Go 1.1.
import sys
import re
output = sys.stdin.readlines()
r = re.compile(r'write\(2, "(.+?)", \d+\)\s+= \d+')
print "".join([x.replace(r'\n', "\n").replace(r'\t', "\t") for x in sum([r.findall(o) for o in output], [])])
#!/bin/bash
# Pass the name of the Golang process that needs killing as the first argument to this script.
PID=$(pgrep -f $1)
echo "Killing pid $PID"
strace -p "$PID" -ewrite 2>&1 | grep "write" | python format_stacktrace_from_strace.py &
sleep 1
kill -QUIT $PID
echo "done"
@joonas-fi
Copy link

warning to anybody trying this: strace by default truncates the values sent to write, so you'll lose output

https://stackoverflow.com/a/6672902

@matheusd
Copy link

I suggest adding the following, to at least show the partial path of clipped lines.

< r = re.compile(r'write\(2, "(.+?)", \d+\)\s+= \d+')
---
> r = re.compile(r'write\(2, "(.+?)"\.{0,3}, \d+\)\s+= \d+')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment