如何通过kill -3命令捕获线程转储并将结果输出至指定文件?
Absolutely, there's a way to capture the thread dump from kill -3 directly into a file without messing with VM startup parameters! Let me break down how this works and the methods you can use:
1. If you haven't started your JVM yet (pre-configure for future dumps)
When you launch your Java application, you can redirect its standard error stream (stderr) to a file right away. Since kill -3 triggers the JVM to write the thread dump to stderr, all subsequent dumps will automatically go into that file:
java -jar your-application.jar 2> /tmp/thread-dumps.log &
Later, whenever you run kill -3 <your-jvm-pid>, the thread dump will be appended to /tmp/thread-dumps.log.
2. If the JVM is already running (no restart needed)
If your JVM is up and you don't want to restart it, you can leverage Linux's /proc filesystem to tap into the JVM's stderr output:
- Open a terminal and run this command to listen to the JVM's stderr and write to your target file:
tail -f /proc/<your-jvm-pid>/fd/2 > /tmp/latest-threaddump.txt - In another terminal, send the SIGQUIT signal as usual:
kill -3 <your-jvm-pid> - Go back to the first terminal and press
Ctrl+Cto stop thetailcommand. Your thread dump will be in/tmp/latest-threaddump.txt.
A quick note: This method will capture all stderr output from the JVM during the time tail is running, so you might see other log entries mixed in with the thread dump. If you want a cleaner capture, you can filter the output (e.g., grep for lines starting with "Full thread dump"), but that adds a bit more complexity.
Also, just a reminder: While kill -3 works, jstack is purpose-built for this exact task and avoids the stderr mixing issue entirely. But if you're stuck using kill -3 for some reason, the above approaches get the job done.
内容的提问来源于stack exchange,提问作者Cork Kochi

