【问题标题】:Referencing Bash jobs in other jobs在其他工作中引用 Bash 工作
【发布时间】:2013-08-06 16:13:53
【问题描述】:

我想在另一个后台 Bash 作业中引用一个后台 Bash 作业。这可能吗?

例如,假设我开始了一项后台工作:

$ long_running_process &
[1] 12345

现在我想在该工作完成时发生一些事情,所以我可以使用wait

$ wait %1 && thing_to_happen_after_long_running_process_finishes

但是,这会阻塞,我希望我的终端回来做其他事情,但是 Ctrl+Z 什么都不做。

首先尝试在后台启动它却失败了:

$ { wait %1 && thing_to_happen_after_long_running_process_finishes; } &
[2] 12346
-bash: line 3: wait: %1: no such job
$ jobs
[1]-  Running     long_running_process &
[2]+  Exit 127    { wait %1 && thing_to_happen_after_long_running process_finishes; }

有没有办法在另一个后台作业中使用wait 引用一个作业?

我在使用 GNU Bash 4.1.2(1)-release 时看到了这种行为。

【问题讨论】:

    标签: bash shell jobs job-control


    【解决方案1】:

    shell 只能wait 在它自己的孩子上。由于后台作业会创建一个新的 shell,因此该 shell 中的 wait 只能等待其自己的子代,而不是其父代的子代(即背景等待分叉的 shell)。对于您想要的,您需要提前计划:

    long_running_process && thing_to_happen_after &
    

    还有一种选择:

    long_running_process &
    LRP_PID=$!
    
    { while kill -0 $LRP_PID 2> /dev/null; do sleep 1; done; thing_to_happen_after; } &
    

    这将设置一个循环,尝试每秒 ping 一次您的后台进程。处理完成后,kill 将失败,并继续进行后处理程序。它具有轻微风险,即您的进程将退出并且另一个进程将在检查之间获得相同的进程 ID,在这种情况下,kill 会变得混乱并认为您的进程仍在运行,而在事实上它是新的。但这风险很小,实际上如果thing_to_happen_after延迟一点,直到没有ID为$LRP_PID的进程,这可能是可以的。

    【讨论】:

    • 认为可能是这样。该死的。
    【解决方案2】:

    试试这样的:

      x2=$(long_running_process && thing_to_happen_after_long_running_process_finishes ) &
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-27
      • 1970-01-01
      • 2012-04-20
      • 1970-01-01
      • 1970-01-01
      • 2017-12-29
      相关资源
      最近更新 更多