Friday, July 15, 2005

check process is running .sh

You think that's all there is to it? Come on, users are much cleverer
than that! How about one of these tests next? Could save you time
later explaining why the users latest work has gone missing.
Example file exists

if [ ! -f $infile ]
then
echo "Input file [$infile] not found - Aborting"
exit
fi

Note the use of the test not flag (!) in front of the -f (file exists)
flag. Or how about:
Example verify

if [ -f $outfile ]
then
echo "Output file [$outfile] already exists"
/usr/5bin/echo "Okay to overwrite? ( y/n ) : \c"
read answer
if [ "$answer" = "n" ] || [ "$answer" = "N" ]
then
echo "Aborting"
exit
fi
fi

Well, it might work. But there is a failing with this second example.
The test of the user answer tests for a "NO!" response. If the user
misses the key, it will carry on. Far better to test for a "YES!"
response which if missed just fails safe. Revise the test line to:

if [ "£answer" != "y" ] && [ "$answer" != "Y" ]

Note the use of the logical and (&&) instead of the logical or (||) here.

[vsequei@sequeira chapter10]$ more check_process.sh
#!/bin/bash

process="/usr/sbin/httpd"
start="service httpd restart"

ps ax | awk '{print $5}' | grep -q "^$process$" || {
# Apparently not running, so start the process
eval "$start"
exit $?
}

exit 0

[vsequei@sequeira chapter10]$ more check_port.sh
#!/bin/bash

port="80"
restart="service httpd restart"

netstat -ln | awk '/^tcp/ {print $4}' | grep -q ":$port$" || {
# Apparently not listening, so run restart command
eval "$restart"
exit $?
}

exit 0
[vsequei@sequeira chapter10]$

just found mysqld had died for the second time in a week, nothing
obvious, so had a search for a good script to check and restart if
necessary. I'm clueless when it comes to shell scripting, and even if
I was I'd still search - it's the kind of thing where it would be easy
to miss something obvious. I was suprised to find…nothing half-useful
(is it so obvious?), so ended up having a go anyway.
Plan B: use the blog, Luke. Below is what I've got (as
/etc/cron.hourly/mysql.checker), if anyone has something better,
please drop in a comment ;-)

#!/bin/sh
if ps -A | fgrep mysqld > /dev/null; then
echo mysqld is running
else
echo mysqld is NOT running
/etc/init.d/mysql start
fi

The script /etc/init.d/mysql I think is mysql.server which comes with
the MySQL source, I may have tweaked it.

# Luke Gorrie Says:
February 15th, 2005 at 17:22

In Erlang we use a "supervisor" process that starts the worker. The
supervisor's job is to immediately restart the worker if it terminates
abnormally. The suprevisor should get an active notification about the
child terminating (like Unix SIGCHLD) instead of polling or being
invoked manually.

Here's a simple Erlang-style supervisor in bourne shell:

#!/bin/sh
"$@" || exec "$0" "$@"

NB: Like an Erlang supervisor this is properly tail-recursive. :-)

0 Comments:

Post a Comment

<< Home