如何捕获进程Id并在该进程在bash脚本中完成时添加触发器?

时间:2016-04-19 04:00:38

标签: bash shell unix triggers background-process

我正在尝试创建一个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,而不是jar文件的PID。

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

2 个答案:

答案 0 :(得分:2)

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

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"

答案 1 :(得分:1)

我不认为你会四处走动,直到你再也看不到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' & )