If you hate when a service crashes, or you forget to restart it yourself after changes. This could be a solution.


#!/bin/bash
#openvpn
if [[ ! $(pgrep openvpn) ]]; then
	/etc/init.d/openvpn start >/dev/null 2>&1
fi

#dns
if [[ ! $(lsof -i :53) ]]; then
	/etc/init.d/pdns start >/dev/null 2>&1
fi

#httpd
if [[ ! $(lsof -i :80) ]]; then
	/etc/init.d/httpd start >/dev/null 2>&1
fi

#mysqld_safe
if [[ ! $(lsof -i :3306) ]]; then
	/etc/init.d/mysqld start >/dev/null 2>&1
fi

#dovecot
if [[ ! $(lsof -i :143) ]]; then
	/etc/init.d/dovecot start > /dev/null 2>&1
fi

# postfix
if [[ ! $(pgrep master) ]]; then
	/etc/init.d/postfix start > /dev/null 2>&1
fi

# ircd
if [[ ! $(lsof -i :6667) ]]; then
	/etc/init.d/ngircd start > /dev/null 2>&1
fi

Okay there is two ways i check for running services.

pgrep and lsof.

pgrep <process name>: This is the same as doing

ps aux|grep <process name>

But instead of returning something like this...

# ps aux|grep ngircd

ngircd 7281 0.0 0.1 39192 1080 ? Ss 2019 3:58 ngircd
root 30490 0.0 0.0 103328 948 pts/0 S+ 18:32 0:00 grep --color=auto ngircd

It returns something like this...

# pgrep ngircd

7281

If you notice the 7281. Thats the process ID for 'ngircd'

Now, you can do the same thing with lsof.. It checks if :<port> is open.. For example

# lsof -i :6667

COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
ngircd 7281 ngircd 7u IPv4 4532474 0t0 TCP my.server.com:ircu-3 (LISTEN)
ngircd 7281 ngircd 10u IPv4 50056432 0t0 TCP

Thats telling you that there is a listening service on port 6667, Which can be used for any TCP/UDP based port.

So with lsof/pgrep explained.. The script above is how you can check if services are running. You just need to know the port, or process name.

Enjoy!