gpt4 book ai didi

Bash kill 后台命令 block

转载 作者:行者123 更新时间:2023-11-29 09:14:35 25 4
gpt4 key购买 nike

我有一些 bash 脚本,我在后台放置了一个命令 block ,然后想杀死它们

#!/bin/bash
{ sleep 117s; echo "test"; } &
ppid=$!
# do something important
<kill the subprocess somehow>

我需要找到一种方法来终止子进程,这样如果它仍在休眠,那么它就会停止休眠,并且不会打印“测试”。我需要在脚本中自动完成,所以我不能使用另一个 shell。

到目前为止我已经尝试过的:

  1. kill $ppid - 根本不会终止 sleep (也有 -9 标志), sleep ppid 变为 1 但不会打印测试
  2. kill %1 - 结果与上面相同
  3. kill -- -$ppid - 它提示 kill: (-30847) - No such process(子进程仍然在这里)
  4. pkill -P $ppid - 测试已打印

我该怎么做?

最佳答案

只需更改您的代码即可:

{ sleep 117s && echo "test"; } &

来自 bash man:

command1 && command2

command2 is executed if, and only if, command1 returns an exit status of zero.

演示:

$ { sleep 117s; echo "test"; } &
[1] 48013
$ pkill -P $!
-bash: line 102: 48014 Terminated sleep 117s
$ test

[1]+ Done { sleep 117s; echo "test"; }



$ { sleep 117s && echo "test"; } &
[1] 50763
$ pkill -P $!
-bash: line 106: 50764 Terminated sleep 117s

关于Bash kill 后台命令 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28303055/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com