我编写了一个bash脚本,它使用cat将一个文件的内容写入另一个文件。然而,我希望被写入的文件被清空,基本上每次都被写入。我的当前代码只在开始时清空文件。
守则:
#!/bin/ash
while true
do
cat /dev/rs232 > /tmp/regfile
> /dev/rs232
sleep 1
> /tmp/regfile
done编辑:为了使目的更清楚一点,我尝试用另一个程序(将输出发布给make )来读取/tmp/regfile,它没有直接读取/dev/rs232的能力(所以我的程序应该是解决这个问题的方法)。/dev/rs232不断地接收一个新字符串。sleep 1是因为它只能每秒钟发布一次。
发布于 2021-07-08 13:18:58
首先,您必须不断地从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发布于 2021-07-08 12:22:40
清空文件的一种方法,>filename
如果您想提高效率,那么也有,truncate -s 0 filename
https://stackoverflow.com/questions/68299586
复制相似问题