本資料はcrontabの設定などについて記したものです。
Linuxでは、OSの起動と同時に実行させたいプログラムは、/etc/init.dや/etc/initなどのディレクトリの下に
自動起動スクリプトや設定ファイルを置いて管理します。
このディレクトリ内におかれたファイルを参照して、システムはシステムの設定や、
システムの管理と提供するサービスに必要なデーモンプログラムの起動を行います。
しかし、これはシステムワイドで利用するデーモンプログラムなどの起動が目的で、
個別のユーザが彼自身の権限で実行したいプログラム(fetchmailなど)などを起動するには向いていません。
管理者権限で自動起動スクリプトを用意して、内部でsuやsudoを使うことも可能ですが、システムの見通しが悪く管理が面倒になります。
マシンの起動と同時に一般ユーザ権限でプログラムを実行するのに、cronが利用できます。
cronはLinuxで使われる基本的なプログラムスケジューラであり、
分単位の任意の時刻をして定期的にプログラムをバックグラウンドで起動することができます。
このcronの機能の中には、時刻指定ではなくOSの起動時を指定してプログラムを起動する機能が含まれています。
通常のcrontabの設定で、
分 時 日 月 週
の5つの値を設定する箇所にその代わりに、
@reboot
という設定句を設定することで、OSの起動時にプログラムを起動することができます。
設定例を、crontab -l で表示したものが以下になります。
% crontab -l -u user # Edit this file to introduce tasks to be run by cron. # # Each task to run has to be defined through a single line # indicating with different fields when the task will be run # and what command to run for the task # # To define the time you can provide concrete values for # minute (m), hour (h), day of month (dom), month (mon), # and day of week (dow) or use '*' in these fields (for 'any').# # Notice that tasks will be started based on the cron's system # daemon's notion of time and timezones. # # Output of the crontab jobs (including errors) is sent through # email to the user the crontab file belongs to (unless redirected). # # For example, you can run a backup of all your user accounts # at 5 a.m every week with: # 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/ # # For more information see the manual pages of crontab(5) and cron(8) # # m h dom mon dow command @reboot /home/user/bin/user.sh
この設定により、OS起動のタイミングで一般ユーザであるuserの~/bin/user.shが自動的に起動されます。
この方法であれば、自動実行スクリプトや設定ファイルの作成も、
その設置に管理者権限が必要になることもありません。
以上、管理者権限ではなく、一般ユーザ権限をOS起動と同時にバックグラウンドでプログラムを実行させる方法についてでした。