2

I am trying to improve this one liner I use as an (abused) docker-compose healthcheck that runs inside a container:

ps -C program.bin -o pid,pcpu --no-headers | awk '$2 > 98 {print $1}' | xargs kill -9

In current form, I filter the PIDs with CPU utilization over 98% and kill any matching PID right away.

However, I would like to kill only if an exact number of resulting PIDs have the high utilization (in other words, if one program.bin PID has CPU over 98%, don't kill it, but if 2 of them meet the criteria, kill them both). Any pointers on how to do this? Thanks!

2
  • 2
    Find the cause of the high usage before becoming a serial killer! Jun 25 at 16:30
  • Looks like you've reached the point where a one liner is no longer enough. Write a script, or fix the actual underlying issue
    – Panki
    Jun 25 at 17:15
2
... | awk '
$2 >= 98 {c++; m[$1]} 
END { if (c >=2 ) for(i in m) print i }' | xargs -r kill -9

Store the process whose burn a lot of resources in an array and print them if and only more than n process are above the threshold, otherwise print nothing.

The -r option instruct xargs to quit without executing the command if no argument are given. Otherway execute the kill.

1
  • 1
    I had a hunch that storing the results in an array might be the key, but wasn't sure how to properly do it! Thank you so much, this is exactly what I needed!
    – reallove
    Jun 28 at 15:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.