Wednesday, June 8, 2011

Daemonizing a script in UNIX

There are occasions when you would want to execute a script as soon as your OS boots.
The point of interest is a script my_good_work written in your favorite programming/scripting language. I have taken the example of a Dtrace script and so my_good_work becomes my_good_work.d for this post.

I describe how you do this in a UNIX based OS (Solaris to be precise)
Demonizable scripts need to be placed in /etc/init.d/. In my case, I created the boot-driver script dtrace which does nothing but sets up the command line for running my_good_work.d with its runnable parameters. The dtrace script plugs into the OS's boot framework. You need to specify actions that need to be taken when the script is executed with start and stop as command line arguments.

For example, I did (in bash)

case "start"
                 // start my_good_work.d script
                 // /usr/sbin/dtrace -s ~/my_good_work.d

case "stop"
                 // kill `pgrep dtrace`
              
esac

You can find a plethora of examples to do this in the /etc/init.d/ folder.

After this, you need to create a hard link to dtrace and place it in one of /etc/rcN.d/ folders. It really doesn't matter what N is (as far as I know). You need to create the hardlink as [S|K]NNdtrace.
S - Use this if you want to execute the script during startup
K - Use this if you want to execute the kill the script during shutdown
NN - Sequence number that is used to specify the order in which the scripts are executed.

In my case, I did

# ln /etc/init.d/dtrace /etc/rc2.d/S09dtrace

And you are done!

Note:
- Creating a copy and renaming it instead of creating a hard link will most likely won't work, neither will a soft link
- You need to be root for doing this entire exercise, because messing with boot options is not a joke!