Dmitry Leskov
 

Running programs on Linux boot up

The other day I needed to configure a Linux VM to run a few programs at system startup. It turned out that there is no single way to accomplish that that would work across all major Linux distros and Unix flavors.

First of all, while the implementation of the system startup daemon in most Linux distributions used to be compatible with the good old System V init, BSD and derivatives always did it differently. Then, the init daemon has numerous shortcomings, but even the major Linux vendors could not have agreed on a single replacement, and some of them elected to devise their own. While Fedora, openSUSE, Mandriva and a bunch of others have been switching over to systemd, Ubuntu has created Upstart, Arch Linux adopted BSD-style init, and Gentoo always had a custom implementation with named runlevels. And for Mac OS X Apple had created SystemStarter, only to replace it with launchd in Mac OS X 10.4.

However, the programs in question are not daemons. They just need to perform a certain task and terminate, and they better do that at the very end of the boot process, or at least after networking starts. The collective wisdom of the Internet says that I could simply add the respective commands to the /etc/rc.local script that runs “at the end of each mutli-user runlevel”. Needless to say, FreeBSD and company do not have runlevels, but at least there is /etc/rc.local, which was heavily used in the past, but now remains mostly for backward compatibility. But (surprise!) on Mac OS X that file is called /etc/rc.common. Arrrgh!

Hope is not lost though. It turned out that there is one place on most systems and that place is even within the reach of an ordinary (i.e. unprivileged) user – crontab files!

Just run crontab -e and use the special string @reboot in place of the time and date fields:

@reboot command

System crontabs often have an extra field for the account username:

@reboot user command

Important: You better specify the full path to the command or, if you have many cron jobs, put a PATH line at the top of your crontab file. Also, make sure to end the last line in your crontab file with a newline character or it won’t work! For more cron troubleshooting tips, refer to this collection on AskUbuntu.

The only caveat to this solution is that on most systems cron cannot distinguish between a system reboot and a mere restart of the cron daemon itself. But a restart is very unlikely to occur, except when you are debugging your crontabs.

Specifically on Debian and derivatives, cron is capable of identifying restarts by creating a file crond.reboot in the /var/run directory. That directory is cleared early on system boot, so if the file does not exist, cron knows it starts for the first time after a system bootstrap and runs the @reboot tasks.

Tags: , , ,

« | »

Talkback

* Copy This Password *

* Type Or Paste Password Here *