【问题标题】:Emtpy a file while using cat on it使用 cat 清空文件
【发布时间】:2021-07-08 10:08:09
【问题描述】:

我编写了一个 bash 脚本,它使用 cat 将一个文件的内容写入另一个文件。但是我希望正在写入的文件被清空,基本上每次都被写入。我当前的代码只在启动时清空文件。

代码:

#!/bin/ash
while true
do
cat /dev/rs232 > /tmp/regfile
> /dev/rs232
sleep 1
> /tmp/regfile
done

编辑: 为了使目的可能更清楚一点,我试图用另一个程序读取/tmp/regfile(将输出发布到MQTT代理),它没有能力直接读取/dev/rs232(所以我的程序是应该是解决方法)。 /dev/rs232 不断收到一个新字符串。 sleep 1 是因为它只能每秒发布一次。

【问题讨论】:

  • 这是使用fifo的目的
  • 问题不是很清楚......如果你这样做cat something > file > 每次都会覆盖文件......如果你想追加,你应该这样做>>
  • emptied, essentially everytime it has been written into 所以文件总是空的?这是XY问题吗?你想ex。而是保留文件中的最后一行?
  • 你可以写信给/dev/null;首先写信给/tmp/regfile 的目的还不清楚。你有没有尝试阅读/tmp/regfile的内容?
  • sleep 1 so the mqtt publisher has time to publish 不要使用睡眠作为同步。采用真正的同步机制。

标签: bash shell cat


【解决方案1】:

首先,您必须不断地从 rs232 读取,因为很可能设备文件没有任何缓冲区。因此,您必须自己缓冲输入。然后,每 1 秒,您可以将缓冲区刷新到文件中。

# Using cat to have hopefully 4K buffer in pipe
# Would be better to use `stdbuf -o4K` explicitly.
cat /dev/rs232 |
while true; do
     # reading data for one second
     data=$(timeout 1 cat)  # TODO: handle errors, so it does not loop endlessly
     # Write data to regfile.
     # This should be fast enough or the buffer from the device
     # should be big enough so that `cat /dev/rs232` will not notice
     # that we stopped reading from stdin.
     # Ideally, this would be asynchronously in another process or thread.
     printf "%s" "$data" > /tmp/regfile
done

【讨论】:

  • 感谢您的回答,我会尝试使用它,看看效果如何。关于我必须看到的同步机制,因为正在运行的环境没有互联网连接,也没有太多的库存储空间 (
【解决方案2】:

清空文件的一种方法, >filename

如果您想提高效率,那么还有, truncate -s 0 filename

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-22
    • 1970-01-01
    • 2015-12-25
    • 2012-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多