Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

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

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

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
Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away