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

标签 bash pipe sh background-process

假设我有如下所示的 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/

相关文章:

读取和保存变量时的 Bash

Linux 命令行语法 - 在 ping 请求后管道输入命令

image - 如何使用 2 个图像 ffmpeg 创建图像

c - 管道数组 : Will parent process load the array fast enough?

bash - 在哪些 shell 语句中,使用或不使用双引号扩展变量是 100% 等效的?

linux - 如何获取 shell 脚本所在位置的完整路径

bash - 如何将命令的输出视为文件?

bash - 如何在bash中用逗号分隔grep结果?

linux - 如何使用shell变量更改特定位置的字符

perl - 如何使用 bash 或 perl 在 Unix 上查找 find2perl 脚本的路径