erotsppa
erotsppa

Reputation: 15071

Why does my process counting script give false positives?

I have the following bash script, that lists the current number of httpd processes, and if it is over 60, it should email me. This works 80% of the time but for some reason sometimes it emails me anyways when it is not over 60. Any ideas?

#!/bin/bash
lines=`ps -ef|grep httpd| wc -l`
if [ "$lines" -gt "60" ]
then
        mailx -s "Over 60 httpd processes" [email protected] < /dev/null
fi

Upvotes: 2

Views: 446

Answers (6)

Alok Singhal
Alok Singhal

Reputation: 96241

  1. There is a delay between checking and emailing. In that time, some httpd processes might finish, or start, or both. So, the number of processes can be different.
  2. You are including the grep process in the processes (most of the time, it could happen that the ps finishes before grep starts). An easy way to avoid that is to change your command to ps -ef | grep [h]ttpd. This will make sure that grep doesn't match grep [h]ttpd.
  3. On linux, you have pgrep, which might be better suited for your purposes.
  4. grep ... | wc -l can usually be replaced with grep -c ....
  5. If you want to limit the number of httpd requests, I am sure you can set it in apache configuration files.

Upvotes: 5

gregf
gregf

Reputation: 1101

This probably doesn't solve your issue but you could simplify things by using pgrep instead.

Upvotes: 1

ghostdog74
ghostdog74

Reputation: 343097

you can do it this way too, reducing the use of grep and wc to just one awk.

ps -eo args|awk '!/awk/&&/httpd/{++c}
END{
    if (c>60){
        cmd="mailx -s \047Over 60\047 root"
        cmd | getline
    }
}'

Upvotes: 0

Davide
Davide

Reputation: 17838

grep httpd finds all processes that include httpd in their name, including possibly grep httpd itself, and perhaps other ones.

Upvotes: 4

Ken
Ken

Reputation: 2944

"ps -ef|grep httpd" doesn't find just httpd processes, does it? It finds processes whose full (-f) listing in ps includes the string "httpd".

Upvotes: 1

bmargulies
bmargulies

Reputation: 100186

You've probably thought of this, but ...

At time t0, there are 61.

At time t1, when you read the email, there are 58.

Try including the value of $lines in the email and you'll see.

Or try using /proc/*/cmdline, it might be more reliable.

Upvotes: 4

Related Questions