I was looking for a simple solution without having to install additional stuff and compatible with common hostings that allow SSH access.
I've ended up with this setup for my chat server:
-rwxr-xr-x 1 crazypoems psacln 309 ene 30 14:01 checkChatServerRunning.sh
-rw-r--r-- 1 crazypoems psacln 3018 ene 30 13:12 class.chathandler.php
-rw-r--r-- 1 crazypoems psacln 29 ene 30 14:05 cron.log
-rw-r--r-- 1 crazypoems psacln 2560 ene 29 08:04 index.php
-rw-r--r-- 1 crazypoems psacln 2672 ene 30 13:29 php-socket.php
-rwxr-xr-x 1 crazypoems psacln 310 ene 30 14:04 restartChatServer.sh
-rwxr-xr-x 1 crazypoems psacln 122 ene 30 13:28 startChatServer.sh
-rwxr-xr-x 1 crazypoems psacln 224 ene 30 13:56 stopChatServer.sh
And the scripts:
startChatServer.sh
#!/bin/bash
nohup /opt/plesk/php/5.6/bin/php -q /var/www/vhosts/crazypoems.org/httpdocs/chat/php-socket.php > /dev/null &
stopChatServer.sh
#!/bin/bash
PID=`ps -eaf | grep '/var/www/vhosts/crazypoems.org/httpdocs/chat/php-socket.php' | grep -v grep | awk '{print $2}'`
if [[ "" != "$PID" ]]; then
echo "killing $PID"
kill -9 $PID
else
echo "not running"
fi
restartChatServer.sh
#!/bin/bash
PID=`ps -eaf | grep '/var/www/vhosts/crazypoems.org/httpdocs/chat/php-socket.php' | grep -v grep | awk '{print $2}'`
if [[ "" != "$PID" ]]; then
echo "killing $PID"
kill -9 $PID
else
echo "not running"
fi
echo "Starting again"
/var/www/vhosts/crazypoems.org/httpdocs/chat/startChatServer.sh
And last but not least, I have put this last script on a cron job, to check if the "chat server is running", and if not, to start it:
Cron job every minute
-bash-4.1$ crontab -l
* * * * * /var/www/vhosts/crazypoems.org/httpdocs/chat/checkChatServerRunning.sh > /var/www/vhosts/crazypoems.org/httpdocs/chat/cron.log
checkChatServerRunning.sh
#!/bin/bash
PID=`ps -eaf | grep '/var/www/vhosts/crazypoems.org/httpdocs/chat/php-socket.php' | grep -v grep | awk '{print $2}'`
if [[ "" != "$PID" ]]; then
echo "Chat server running on $PID"
else
echo "Not running, going to start it"
/var/www/vhosts/crazypoems.org/httpdocs/chat/startChatServer.sh
fi
So with this setup:
- I manually can control the service with the scripts when needed (eg: maintenance)
- The cron job will start the server on reboot, or on crash