LoginSignup
25
25

More than 5 years have passed since last update.

多重起動を防止する方法

Last updated at Posted at 2013-03-13

作成したシェルスクリプトを多重起動させたくない場合のテクニックです。マルチスレッドなどでいう排他制御ですね。処理前に処理中を示すロックファイルを作成して、処理が完了した際にロックファイルを消す。シェル実行前にファイルがあれば、処理中だから、ダメねってことです。デーモンなどの起動スクリプトでもよく使われている手ですね。

bash
#!/bin/sh
lockfile=lockfile

if [ -f $lockfile ]; then
    echo $0
    exit 1
fi

touch $lockfile

#ここでやりたい処理を書く
echo start
sleep 10
echo end

rm -f $lockfile

■2013/03/14追記
↑のスクリプトだと、少し問題があるので下記のように修正しました。

bash
#!/bin/sh
lockfile=lockfile

ln -s $0 ${lockfile} 2> /dev/null || exit 1

#ここでやりたい処理を書く
echo start
sleep 10
echo end

rm -f $lockfile
25
25
3

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
25
25