1

I want to write a script (in bash or Perl on linux) which monitors the Apache and restarts the Apache in case it exceeds X% CPU. I understand that I need to get the total CPU usage of Apache since it opens child process.

How can I get the total CPU usage of Apache?

Shay
  • 633
  • 2
  • 11
  • 27

3 Answers3

4

Try the following, but make sure to update the Apache-process name with your actual one (mine is httpd):

ps u -C httpd | awk '{sum += $3} END {print sum}'

This will get a list of all apache processes running and sum the %CPU column of ps's output using awk.

newfurniturey
  • 37,556
  • 9
  • 94
  • 102
  • ps u -C apache returns an empty result – Shay Aug 13 '12 at 14:31
  • @Shay is `apache` the name of your apache process? I've seen `httpd` and `apache2`, but never just `apache`? – newfurniturey Aug 13 '12 at 14:34
  • The name is apache2 but with apache2 the command also returns empty – Shay Aug 13 '12 at 14:43
  • @Shay You can try `ps u -U apache`, in this case, `apache` is the user-account running Apache. If this doesn't work, can you verify that Apache is running and, if so, run `ps aux` and display the output so that we can see the process list to get the process or user name? – newfurniturey Aug 13 '12 at 14:56
  • Is it correct to sum the cpu percent of all apache child process? Each process can run on a different cpu, no? – Shay Aug 14 '12 at 11:18
  • @Shay Are you saying that you want the total CPU Percentage for Apache - per CPU? My method above will give you the **total** CPU utilization for Apache (including the child processes); I may be mistaken, but I don't think that there is a way to determine a per-CPU percentage. – newfurniturey Aug 14 '12 at 12:43
  • If one single apache process eats up 100% CPU (that is, one core) over a longer period there must be something wrong, no need to sum up the CPU usage of multiple processes. – scai Aug 14 '12 at 14:39
  • @scai The OP's question asks for the total, or did I misread? – newfurniturey Aug 14 '12 at 14:42
  • @newfurniturey yes and your answer is basically correct. Yet it doesn't help much to geht the total CPU usage of all processes in my opinion. – scai Aug 14 '12 at 14:47
1

this will return sum load of parent apache process and all child processes, in percents, without any additional info, so that you can easily use this script in any way:

ps --no-heading -o pcpu -C httpd | awk '{s+=$1} END {print s}'
Viktor
  • 392
  • 2
  • 8
0

This will list you the total CPU usage of each apache2 process:

ps u -C apache2 | awk '{print $3}' | grep -v "%CPU"

Note, however, that the total (=average) CPU usage might be rather low even if the current CPU usage is high, especially for long running processes.

scai
  • 20,297
  • 4
  • 56
  • 72