1

我需要开发一个 shell 脚本,如果它们的另一个实例正在运行,它将不会启动。

如果我构建一个监控自身的 test.sh,我需要知道它是否已经在运行然后中止,否则(如果它以前没有运行)我可以运行

#!/bin/bash

loop() {
    while [ 1 ]; do
        echo "run";
        #-- (... omissis ...)
        sleep 30
      done
 }

 daemon="`/bin/basename $0`"

 pidlist=`/usr/bin/pgrep $daemon | grep -v $$`
 echo "1:[ $pidlist ]"

 pidlist=$(/usr/bin/pgrep $daemon | grep -v $$)
 echo "2:[ $pidlist ]"

 echo "3:[ `/usr/bin/pgrep $daemon | grep -v $$` ]"

 echo "4:["
 /usr/bin/pgrep $daemon | grep -v $$
 echo "]"

 if [ -z "$pidlist" ]; then
      loop &
 else
      echo "Process $daemon is already running with pid [ $pidlist ]"
 fi

 exit 0;

当我第一次运行上面的脚本(没有以前的实例运行)我得到这个输出:

1:[ 20341 ]
2:[ 20344 ]
3:[ 20347 ]
4:[
]

我不明白为什么只有第四次尝试没有返回任何东西(如预期的那样)。我的脚本有什么问题?我是否必须在临时文件上重定向第四个命令的输出,然后查询该文件以确定我是否可以运行(或不运行)循环功能?

谢谢有人会帮助我!

4

1 回答 1

0

Sub-shells...the first three are run in sub-shells and hence $$ has changed to the PID of the sub-shell.

Try using:

PID=$$
pidlist=`/usr/bin/pgrep $daemon | grep -v $PID`
echo "1:[ $pidlist ]"

Etc. Since the value of $PID is established before the sub-shell is run, it should be the same for all of the commands.

Is this process going to be popular enough that other people want to run the same daemon on the machine? Maybe you never have multiple users on the machine, but remember that someone else might be wanting to run the command too.

于 2013-05-08T12:59:48.897 回答