[Gloucs] What's wrong with this code?

Glyn Davies glynd at walmore.com
Tue Jul 31 22:40:29 BST 2007


Andy Teague wrote:
> Glyn Davies wrote:
>> No prizes for getting the answer right as I've found it and feel free 
>> to spot the problem immediately and make me look a fool.
>>
>> What's wrong with this line of code. Okay, other than it being a 
>> rubbish way of testing that your gateway is available?
>>
>> if [ "$(ping -c 1 192.168.1.200 | grep '1 received')" != "" ]
>>
>> P.S. I expect I'll learn of other ways in which it is 'wrong' and not 
>> just mine.
>>
>
> well - it sort of worked for me, (as a code fragment - see below) with 
> some caveats:
> a) it assumes ping is on your path, may not be true if running in 
> cron, same for grep
> b) it assumes that ping success means gateway is funtional - OS could 
> still be unavailible
> c) it tells you nothing about the link out of the gateway
> d) it assumes your ping wont hang indefinately (ie it does time out)

Well, you got it with d)

If the gateway, isn't there then ping just hangs.

I discovered this as this line of code was in a cron  job running every 
5 minutes. Over the weekend, we had some power glitches in the FoD. The 
server (on which this code was running) is protected by UPS. The 
firewall isn't. So, I get a call to say 'the server is slow' and 
discovered approx. 400 instances of the cron job waiting for a ping 
reply that would never come. I then made an even better mistake by 
running killall ping which while clearing the cron jobs, also caused the 
sending of 400 'your cron job' emails and brought the server briefly to 
its knees.

The lessons for me were:
a) read man pages better. AIUI now, ping -c -1 means ping until you have 
received 1 reply packet NOT just sent one ping packet. Quite why you 
would want that function I don't know. You need to set a timeout using 
-w to get around the 'missing gateway problem'
b) the classic, test for failures too.

and I suppose
c) virtually everyone on the planet is a better programmer than me.

-- 
Best Regards
Glyn Davies



More information about the gloucs mailing list