检测工具是否已在执行但仅适用于当前用户

rea*_*ebo 8 bash

直到现在我用

pidof -o %PPID -x "my-tool"
Run Code Online (Sandbox Code Playgroud)

检测最终运行的 my-tool 实例的 pid。

这是 my-tool 文件的简短版本,一个可执行的 bash 脚本

#!/bin/bash 

if pidof -o %PPID -x "my-tool"; then
   echo "Already running"
   exit 1
fi

 ... if not running go on 
Run Code Online (Sandbox Code Playgroud)

但是现在我需要允许每个用户有一个实例,每个机器多个实例,所以我们甚至可以在同一时刻运行 100 个 my-tool,但每个用户只能运行 1 个。

请注意,我需要一个测试来创建类似单例的东西。如果该工具将启动并且有另一个实例正在运行,它将自行关闭。

简而言之:我需要一个 bash 脚本可以检测自身是否已经为当前用户运行,在这种情况下它必须退出。

如何 ?

ter*_*don 11

使用pgrep来代替:

pgrep -cxu $USER -f my-tool
Run Code Online (Sandbox Code Playgroud)

使用的选项是:

   -c, --count
          Suppress  normal  output; instead print a count of matching pro?
          cesses.  When count does not match anything, e.g. returns  zero,
          the command will return non-zero value.
   -x, --exact
          Only match processes whose names (or command line if -f is spec?
          ified) exactly match the pattern.
   -u, --euid euid,...
          Only match processes whose effective user ID is listed.   Either
          the numerical or symbolical value may be used.
Run Code Online (Sandbox Code Playgroud)

如果你想在一个 bash 脚本中使用它来检查它是否已经在运行,你可以使用$0. 这会扩展到当前脚本的路径(例如/home/username/bin/foo.sh),但我们只需要foo.sh. 为了得到这一点,我们可以删除一切到最后的/使用bash的字符串操作工具${0##*/}。这意味着我们可以执行以下操作:

pgrep -cxu $USER -f my-tool
Run Code Online (Sandbox Code Playgroud)

您可能还需要考虑为此使用锁定文件:

   -c, --count
          Suppress  normal  output; instead print a count of matching pro?
          cesses.  When count does not match anything, e.g. returns  zero,
          the command will return non-zero value.
   -x, --exact
          Only match processes whose names (or command line if -f is spec?
          ified) exactly match the pattern.
   -u, --euid euid,...
          Only match processes whose effective user ID is listed.   Either
          the numerical or symbolical value may be used.
Run Code Online (Sandbox Code Playgroud)


hee*_*ayl 7

您可以使用pgrepfo 查找进程是否正在由特定用户执行,如果用户尚未运行,则启动该进程:

#!/bin/bash
if pgrep -u "$USER" my-tool &>/dev/null; then
    echo 'You already have my-tool running'
else
    /path/to/my_tool
fi
Run Code Online (Sandbox Code Playgroud)

环境变量$USER将扩展为当前登录的用户,即运行脚本的用户。因为我们只关心是否my-tool正在运行,所以直接使用ifconstruct退出状态就足够了。

使用此脚本作为启动的包装器my-tool并让用户仅使用它或将其重命名为my-tool并将原始文件重命名my-tool为其他内容(并更改脚本内的名称)。