gpt4 book ai didi

bash - 即使第一个命令的子进程仍在后台运行,也关闭管道

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

假设我有如下所示的 test.sh。目的是通过此脚本运行一些后台任务,不断更新一些文件。如果后台任务由于某种原因终止,则应重新启动。

#!/bin/sh

if [ -f pidfile ] && kill -0 $(cat pidfile); then
cat somewhere
exit
fi

while true; do
echo "something" >> somewhere
sleep 1
done &
echo $! > pidfile

并想像 ./test.sh | 那样调用它otherprogram, e. G。 ./test.sh |猫

管道没有被关闭,因为后台进程仍然存在并且可能会产生一些输出。我如何告诉管道在 test.sh 结束时关闭?有没有比在调用管道命令之前检查 pidfile 是否存在更好的方法?

作为变体,我尝试在 test.sh 末尾使用 #!/bin/bashdisown,但它仍然是等待管道关闭。


我实际尝试实现的目标:我有一个“状态”脚本,它收集各种脚本的输出(uptimefreedateget-xy-from-dbus等),类似于这里的这个test.sh。脚本的输出被传递到我的窗口管理器,它显示它。它也用在我的 GNU 屏幕底线中。

由于使用的一些脚本可能需要一些时间来创建输出,我想将它们从输出集合中分离出来。所以我把它们放在 while true;做脚本; sleep 1; done 循环,如果它还没有运行就开始。

现在的问题是我不知道如何告诉调用脚本“真正”分离守护进程。

最佳答案

看看这是否符合您的目的:(我假设您对 while 循环中的任何命令 stderr 都不感兴趣。如果您愿意,您将调整代码。:-))

#!/bin/bash

if [ -f pidfile ] && kill -0 $(cat pidfile); then
cat somewhere
exit
fi

while true; do
echo "something" >> somewhere
sleep 1
done >/dev/null 2>&1 &
echo $! > pidfile

关于bash - 即使第一个命令的子进程仍在后台运行,也关闭管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12689369/

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