【问题标题】:How to capture a process Id and also add a trigger when that process finishes in a bash script?如何捕获进程 ID 并在该进程在 bash 脚本中完成时添加触发器?
【发布时间】:2016-04-19 04:00:37
【问题描述】:

我正在尝试制作一个 bash 脚本来启动一个 jar 文件并在后台执行它。出于这个原因,我使用nohup。现在我可以捕获java进程的pid,但我还需要能够在进程完成时执行命令。

我就是这样开始的

nohup java -jar jarfile.jar & echo $! > conf/pid

我也从this answer 知道,使用; 将使第一个命令完成后执行。

nohup java -jar jarfile.jar; echo "done"

echo "done" 只是一个例子。我现在的问题是我不知道如何将它们结合起来。如果我先运行echo $!,那么echo "done" 会立即执行。如果echo "done" 先行,那么echo $! 将捕获echo "done" 的PID,而不是jarfile 的PID。

我知道我可以通过轮询来实现所需的功能,直到我不再看到 PID 运行。但我想尽可能避免这种情况。

【问题讨论】:

    标签: bash shell unix triggers background-process


    【解决方案1】:

    使用nohup 启动进程后,您可以使用 bash util wait

    nohup java -jar jarfile.jar &
    pid=$!     # Getting the process id of the last command executed
    
    wait $pid  # Waits until the process mentioned by the pid is complete
    echo "Done, execute the new command"
    

    【讨论】:

      【解决方案2】:

      我认为您不会绕过“轮询直到您不再看到 pid 运行”。 wait 是内置的 bash;这就是你想要的,我敢肯定这正是它在幕后所做的。但由于 Inian 击败了我,这对你来说还是一个友好的函数(以防你想让一些事情并行运行)。

      alert_when_finished () {
        declare cmd="${@}";
        ${cmd} &
        declare pid="${!}";
        while [[ -d "/proc/${pid}/" ]]; do :; done; #equivalent to wait
        echo "[${pid}] Finished running: ${cmd}";
      }
      

      运行这样的命令将产生预期的效果并抑制不需要的作业输出:

      ( alert_when_finished 'sleep 5' & )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-08
        • 1970-01-01
        • 2014-02-27
        相关资源
        最近更新 更多