I had a PHP script that I wanted to keep running in background so that I could get it to perform a task when it received input, but the problem I had was that the PHP script kept timing out, and I wanted the script to run at startup. Here's what I used to solve the problem.
NOTE: You're gonna need admin access to your linux server for this solution to work. (and it only works in unix systems).
daemontools which is a collection of tools for managing UNIX services that includes a tool to monitor your service, and restart if the service dies. I want to run through the install process that I used for my ubuntu 11.10 server. While they are similar to the installation process described at http://cr.yp.to/daemontools.html I had an error during compile: "/usr/bin/ld: make: *** [envdir] Error 1" which I required a slight change to conf-cc, so I'm including that change in my installation instructions so you don't have to
Create a /package directory:
mkdir -p /package
chmod 1755 /package
cd /package
wget http://cr.yp.to/daemontools/daemontools-0.76.tar.gz
gunzip daemontools-0.76.tar
tar -xpf daemontools-0.76.tar
rm -f daemontools-0.76.tar
cd admin/daemontools-0.76
Make a change to the compiler so you don't get the "/usr/bin/ld: make: *** [envdir] Error 1" error
If there is a conf-cc file, then add “–include /path/to/errno.h” to the gcc line. Normally the file is at /usr/include/errno.h.
Compile and set up the daemontools programs:
package/install
Now we need to set up the service to run at start up like this:
Put the lines
start on runlevel [12345]
stop on runlevel [^12345]
respawn
exec /command/svscanboot
into /etc/init/svscan.conf.
Finally, you want to set up the service that you intend to monitor.
daemontools creates a /service directory. under that service directory create a directory for the service you want to run. Maybe you want to start nodejs as a service.
/service/nodejs
now create a run file
vi /service/nodejs/run
#!/bin/sh
echo starting nodejs
cd /path/containing/server.js/... (obviously change this to the correct path or this won't work)
exec node server.js
change the permissions on the nodejs directory and contents to 755
chmod 755 /services/nodejs -R
Because daemontools is running, it will be scanning the /services directory for new services to monitor, and you will find your service starts in a few seconds - just check your system processes using ps auwx and you will see your new service running - and any errors (if there are any)
There's a lot more information on how to manage your services with daemontools in the FAQ files at http://cr.yp.to/daemontools.html but it can be a bit techy
I hope you find this article helpful - please post any comments or corrections you may have below.
P.S. I kinda threw this article together quite quickly as a reminder to myself on how to do this, so will be revisiting this article when I get the chance to cleaning it up and format it better.

