Skip to content

Instantly share code, notes, and snippets.

@andreineculau
Last active October 26, 2016 13:52
Show Gist options
  • Save andreineculau/10834241 to your computer and use it in GitHub Desktop.
Save andreineculau/10834241 to your computer and use it in GitHub Desktop.
Jenkins - kill all subprocesses in the pre- or post-build phase
set +x
# Add this as the 1st build Exec shell
# Only for situations where you have 1 and only 1 executor per machine
# And you don't care about processes being left running after the job run ends
# Look for processes that have a BUILD_ID env var
# that is NOT the same as the current job's BUILD_ID
# nor same as dontKillMe
echo "Killing orphan spawned processes..."
PID_SELF=$$
for PID in $(ps -eo pid,command -u ${USER} | grep -v grep | tail -n+2 | awk '{print $1}' | grep -v ${PID_SELF}); do
cat /proc/${PID}/environ 2>/dev/null | \
grep "BUILD_ID=" | \
grep -v "BUILD_ID=dontKillMe" | \
grep -v "BUILD_ID=${BUILD_ID}" -q && \
echo "Killing $(ps -p ${PID} | tail -1)" && \
kill -9 ${PID}
done || true
set +x
# Add this as a post-build script i.e. with PostScriptPlugin
# Look for processes that have a BUILD_ID env var
# that is the same as the current job's BUILD_ID
# (ignore current process and grep)
echo "Killing spawned processes..."
PID_SELF=$$
for PID in $(ps -eo pid,command -u ${USER} | grep -v grep | tail -n+2 | awk '{print $1}' | grep -v ${PID_SELF}); do
grep "BUILD_ID=${BUILD_ID}" /proc/${PID}/environ -q 2>/dev/null && \
echo "Killing $(ps -p ${PID} | tail -1)" && \
kill -9 ${PID}
done || true
@garlandkr
Copy link

ps auxww | awk '/SimpleHTTPServer/&&!/awk/{system("kill -9 "$2"")}'

@andreineculau
Copy link
Author

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