gpt4 book ai didi

shell - "kill %1"失败并在脚本中打印 "No such process"

转载 作者:行者123 更新时间:2023-12-05 02:58:29 27 4
gpt4 key购买 nike

我目前使用 dash 作为主 shell。
我试着写了一个应该模仿等待的小函数,但是有一些文本。

这是一个最小的工作代码:

#!/bin/dash

wait() {
echo Waiting...
local pid="${1}"; shift
local delay=.250
while kill -0 "${pid}" 2>/dev/null; do
echo Still waiting...
sleep "${delay}"
done
echo Resuming
}

main() {
sleep 3 &
wait %1
}

main

如果将其复制粘贴到破折号 shell 中,您可以看到代码运行良好。
无论如何,如果您尝试将其保存在文件中,它不会。

经过一些故障排除后,我发现删除 2>/dev/null 时,您会看到一条错误消息:kill: No such process, < em>但是使用 command wait "${pid}" 它只是等待它。

例如:

#!/bin/dash

wait() {
echo Waiting...
local pid="${1}"; shift
command wait "${pid}"
echo Resuming
}

main() {
sleep 3 &
wait %1
}

main

作为文件脚本也能正常工作。

我不确定这段代码哪里/哪里出了问题,而且我尝试过的一些方法没有帮助。

在试验中,我尝试将 %1 转换为其 pid,但 jobs -p %1 在子 shell 中(例如 var="$( jobs -p %1)") 严重失败。

有什么建议吗?

最佳答案

Job control在非交互式 shell 中被禁用。使用 set -m 启用它,或者将 -m 附加到 shebang,它就会工作。

例子:

$ dash -c 'sleep 1 & kill %1 && echo success'
dash: 1: kill: No such process

$ dash -m -c 'sleep 1 & kill %1 && echo success'
success

关于shell - "kill %1"失败并在脚本中打印 "No such process",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59008261/

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