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?

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

9 Comments

ps u -C apache returns an empty result
@Shay is apache the name of your apache process? I've seen httpd and apache2, but never just apache?
The name is apache2 but with apache2 the command also returns empty
@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?
Is it correct to sum the cpu percent of all apache child process? Each process can run on a different cpu, no?
|
1

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.

Comments

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}'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.