I am trying to catch the cause of an intermittent %CPU spike in a server with the command: watch -n .5 "ps aux | sort -rk 3,3 | head -n 2" where it displays the process with the highest %CPU every .5 seconds.

However since it is difficult to catch (the event is random and I have no idea how long it lasts), I want to do the following: 1. Reduce the interval (to increase the chance of catching the event) and write the output to a file 2. Since the top process is usually constant anyway, I would like to write only when there is a difference in value between two succeeding outputs (like when the CPU spike occurs) to avoid creating such a huge file.



Forget about watch, this should do, at least theoretically:

while true; do
  # I cut the header first with tail
  cat file <(ps aux | tail -n +2 | sort -rk 3,3 | head -n 2) | sort | uniq | sponge file
  # A certain amount of delay
  sleep 0.1

The only problem is that since CPU usage of each process varies over time, and what you are seeking for is particularly the CPU usage, the effect of uniq is very limited and still a large amount of data is produced. You can use cut to suppress the variables that are not important for you, so that their variation does not increase the number of data points produced.

| improve this answer | |

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.