LoginSignup
7
7

More than 5 years have passed since last update.

二重起動チェック(bashスクリプト)

Last updated at Posted at 2015-07-28

時々必要になるシェルスクリプトの二重起動チェック処理のメモ

ロック機構としてディレクトリを使用する方式。
ディレクトリが作成できたプロセスのみが処理を継続する。
ただし、ディレクトリが不正に残った場合を考えて、ディレクトリを作ったプロセスが居なければ不正なロックとして処理を継続する。

double_start_check.sh
#!/bin/bash

lockdir=/tmp/lock_$(basename $0)
pidfile=$lockdir/pid

function delete_lock() {
    rm -r $lockdir
}

trap 'delete_lock' INT TERM

# 二重起動チェック
mkdir $lockdir
if [ $? != 0 ]; then
    other_cmd_pid=$(cat $pidfile)
    kill -0 $other_cmd_pid
    if [ $? = 0 ]; then
        echo "other process started."
        exit 1
    fi
fi
echo $$ > $pidfile

# スクリプトの主処理

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