serviceコマンドを利用することにより、サービス(デーモン)の起動・再起動・停止・状態取得などを実行することができます。
本資料では、CentOS, Ubuntuを使って確認しました。
serviceコマンドは以下のような使いかたになります。
service スクリプト コマンド オプション
スクリプトとは、/etc/init.d/にあるスクリプト名になります。
以下のように、サービス(デーモン)のスクリプトがあります。 $ ls /etc/init.d/ NetworkManager hidd netconsole setroubleshoot acpid hplip netfs single anacron hsqldb netplugd smartd atd httpd network smb auditd ip6tables nfs squid autofs ipmi nfslock sshd : :
今回はApache(httpd)の起動・再起動・停止・状態取得をしてみます。
$ su - パスワード: # service httpd status httpd is stopped # service httpd start Starting httpd: [ OK ] # service httpd status httpd (pid 7574) is running... # service httpd restart Stopping httpd: [ OK ] Starting httpd: [ OK ] # service httpd status httpd (pid 7606) is running... # service httpd stop Stopping httpd: [ OK ] # service httpd status httpd is stopped
$ sudo service apache2 status Apache is NOT running. $ sudo service apache2 start * Starting web server apache2 [ OK ] $ sudo service apache2 status Apache is running (pid 2178). $ sudo service apache2 restart * Restarting web server apache2 ... waiting [ OK ] $ sudo service apache2 status Apache is running (pid 2281). $ sudo service apache2 stop * Stopping web server apache2 ... waiting [ OK ] $ sudo service apache2 status Apache is NOT running.
/etc/init.dのスクリプトでも同様のことができます。
以下、Apache(httpd)の起動・再起動・停止・状態取得をしてみます。
# /etc/init.d/httpd status httpd is stopped # /etc/init.d/httpd start Starting httpd: [ OK ] # /etc/init.d/httpd status httpd (pid 7764) is running... # /etc/init.d/httpd restart Stopping httpd: [ OK ] Starting httpd: [ OK ] # /etc/init.d/httpd status httpd (pid 7786) is running... # /etc/init.d/httpd stop Stopping httpd: [ OK ] # /etc/init.d/httpd status httpd is stopped
$ sudo /etc/init.d/apache2 status [sudo] password for sakura: Apache is NOT running. $ sudo /etc/init.d/apache2 start * Starting web server apache2 [ OK ] $ sudo /etc/init.d/apache2 status Apache is running (pid 2446). $ sudo /etc/init.d/apache2 restart * Restarting web server apache2 ... waiting [ OK ] $ sudo /etc/init.d/apache2 status Apache is running (pid 2546). $ sudo /etc/init.d/apache2 stop * Stopping web server apache2 ... waiting [ OK ] $ sudo /etc/init.d/apache2 status Apache is NOT running. $
serviceコマンドはシェルスクリプトで作成されています。
$ file /usr/sbin/service /usr/sbin/service: POSIX shell script text executable
# file /sbin/service /sbin/service: Bourne shell script text executable
serviceコマンドを確認したところ、以下の処理がありました。
env -i LANG="$LANG" PATH="$PATH" TERM="$TERM" ...
env -i により環境を引き継がず、LANG, PATH, TERMのみ環境変数を引き継ぐようになっています。
man envの-iオプションの抜粋です。
オプション -, -i, --ignore-environment 継承された環境を無視して、空の環境から始める。
したがって、/etc/init.d/サービス名(スクリプト) コマンドとserviceコマンドの違いは、環境変数を継承するか、継承しないかの違いがあります。