Restarting dead services using cron/bash
by z3n on Jun.11, 2009, under Coding, Linux Happyness
Problem:
Some services keep dieing and there’s nothing much you can do about it, since they don’t restart automatically.
Those services could be httpd/apache, mysqld, sshd, etc
Solution:
This little script will do the job:
pstree | grep httpd | wc -l | awk ‘{if ($1 == 0) system(“service httpd restart”) }’
in this example i’m checking if httpd (apache) is running.
broken down, pstree will list all your running processes,
grep httpd will search for “httpd” string on pstree,
wc -l will count the words from grep httpd, basically will return 0 or 1 if something was found,
and finally awk will check if wc -l is = 0 , meaning that the service / process in question is not running, then will perform the required action, on my example, service httpd restart which will restart apache.
You may also check it by port level as suggested by HTNet :
netstat -ln | grep “:80″ | wc -l | awk ‘{if ($1 == 0) system(“service httpd restart”) }’
You could build up a little .sh file and put it on crontab to check it every minute or whatever you like.
Problema:
Um serviço / processo para de funcionar, como reiniciá-lo automaticamente ?
Solução:
Este script resolve:
pstree | grep httpd | wc -l | awk ‘{if ($1 == 0) system(“service httpd restart”) }’
neste exemplo estou checando se o httpd (apache) está rodando, quebrando os pipes fica assim:
o pstree vai listar todos os processos,
grep httpd irá procurar por httpd no pstree,
wc -l irá contar as palavras no que o grep retorna, basicamente irá retornar 0 ou 1,
awk irá comparar o valor do wc -l , se o processo não estiver rodando ($1 == 0) ele irá executar o comando para reiniciá-lo, neste caso, service httpd restart
Você também pode checar pelas portas, como proposto pelo HTNet:
netstat -ln | grep “:80″ | wc -l | awk ‘{if ($1 == 0) system(“service httpd restart”) }’
Depois é só fazer um .sh e colocar no crontab!