linux - shell 脚本: Redirect output of program to changing files

标签 linux bash shell redirect stdout

我的目标:

我想根据程序的运行时间将程序 foostdout 输出重定向到不断变化的输出文件。

程序foo本身正在bsd套接字上监听到达的数据包并显示其中包含的信息。
因此,本质上,在运行程序 foo 10 分钟后,我希望获得

stdout 输出
  • 文件 bar_0.dat 内的第一分钟
  • 文件 bar_1.dat 内的第二分钟
  • ...
  • 文件 bar_9.dat 内的第 10 分钟

是否可以在 shell 脚本中实现此目的,如果可以,我该如何实现此目的?

到目前为止我所做的事情:

我只管理这个解决方案,其中程序每分钟后重新启动并重定向到新的输出文件:

#!/bin/bash
for i in {0..9}
do
  timeout 60s foo > "bar_${i}.dat"
done

但是,我希望程序 foo 连续运行而不必重新启动它,因为我意识到我丢失了一些到达的数据包(有 20-30 毫秒的间隙运行实例之间)。

最佳答案

让程序写入命名管道 (fifo),然后从该管道获取输出并将其放入文件中。在此示例中,我在后台启动循环,然后立即开始写入命名管道:

mkfifo thepipe

for (( i = 0; i < 10; ++i )); do
    timeout 60 cat thepipe >"bar_$i.dat"
done &

foo >thepipe
rm -f thepipe

或者,使用进程替换:

foo > >( 
    for (( i = 0; i < 10; ++i )); do
        timeout 60 cat >"bar_$i.dat"
    done
)

关于linux - shell 脚本: Redirect output of program to changing files,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50701414/

相关文章:

linux - 使用 popen 创建的 FILE 上的 fclose 发生了什么?

Linux 内核文件系统多线程

bash - 如何制作检查提交消息的 git 预提交 Hook ?

linux - 在 ssh 中使用参数运行多个命令

linux - 使用linux命令随机选择列

linux - EPOLLET 的用例是什么?

arrays - 如何将 bash 脚本数组中的值递增 1?

linux - 使用 Linux 命令删除早于 1 天的子目录中的文件

c++ - IShellDisptach:为什么 FolderItemVerbs::Release() + CoUninitialize() 会崩溃?

shell - 来自数组的输入,供 awk 查找重复项