LoginSignup
17
20

More than 5 years have passed since last update.

root以外のユーザーでupstartを実行する

Posted at

あるスクリプトをroot以外のユーザーでずっと実行させたい、そしてもしプロセスが死んでも再起動して欲しいという事で初めて upstart を使ってみたのでその時のメモ
今回は無限ループするシェルスクリプトをupstartとして登録して挙動を確認する

参考

動作環境

  • Amazon Linux AMI release 2015.03

Upstartのバージョン確認

$ initctl --version
initctl (upstart 0.6.5)
Copyright (C) 2010 Canonical Ltd.

This is free software; see the source for copying conditions.  There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

サンプルシェルスクリプトを作成する

以下のような無限ループするシェルスクリプトを作成してみて確認する

createDateFile.sh
#!/bin/bash

while :
do
  date |xargs echo >> /home/ec2-user/time.txt
  sleep 5
done

試しに実行してみる。

$chmod 755 createDateFile.sh
$./createDateFile.sh

実行すると/home/ec2-user/配下に5秒毎にtime.txtというファイルに時間が追記されるのが確認できます。無限ループなのでCtrl+Cで途中で停止させること

upstartに登録する

upstartにスクリプトの設定は /etc/init/ 配下に配置する。今回は以下のファイルを作成

$sudo vi /etc/init/create-date-file.conf
create-date-file.conf
description "create date file"

start on runlevel [2345]
start on runlevel [!2345]

respawn

exec /home/ec2-user/createDateFile.sh

設定を反映します。

$sudo initctl reload-configuration
$sudo initctl list |grep create
create-date-file stop/waiting

上記の状態ではスクリプトは実行されていないので実行させます。

$sudo initctl start create-date-file
create-date-file start/running, process 2385
$sudo initctl list |grep create
create-date-file start/running, process 2385

起動後は start/running となっているのが確認できます。

またプロセスが起動していることも確認できます。

$ps aux |grep createDate
root      2385  0.0  0.1  11520  1344 ?        Ss   06:23   0:00 /bin/bash /home/ec2-user/createDateFile.sh
ec2-user  2704  0.0  0.0 110404   860 pts/0    S+   06:29   0:00 grep createDate

試しに上記のプロセスをkillしてみます。

$sudo kill -KILL 2385

その後、プロセスを再確認すると別のプロセスIDで起動している事が確認できます。

$ ps aux |grep createDate
root      2767  0.0  0.1  11520  1332 ?        Ss   06:31   0:00 /bin/bash /home/ec2-user/createDateFile.sh
ec2-user  2773  0.0  0.0 110404   860 pts/0    S+   06:31   0:00 grep createDate

rootユーザー以外で実行する

上記だと実行ユーザーが root となってしまいます。上記より、任意のユーザーで実行できるように設定を変更します。今回はec2-userで実行するようにします。

以下のようにファイルを変更します。

create-date-file.conf
description "create date file"

start on runlevel [2345]
start on runlevel [!2345]

respawn

exec `su ec2-user -c "/home/ec2-user/createDateFile.sh"`

また、先ほどのファイルを削除後、再設定して起動させます。

$sudo initctl stop create-date-file
create-date-file stop/waiting
$sudo rm ~/time.txt
$sudo initctl reload-configuration
$sudo initctl start create-date-file

上記実行後、プロセスを確認すると期待したとおりec2-userでプロセスが実行され、/home/ec2-user/time.txtもec2-userの権限となっていることが確認できます。

17
20
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
20