Any way in Bash to write to a file every X seconds without closing it?

5,846

Solution 1

while true; do
  echo "0"
  sleep 30
done > /dev/watchdog

Solution 2

It sounds like you want a daemon:

while sleep 50; do
    echo 0
done > /dev/watchdog

The file handle here will not close until the loop finishes. Note that if execution becomes blocked for >10 seconds for some reason, this could fail. That's unlikely to happen, but it's technically feasible.

You'd do better to write a while condition that includes the conditions for your watchdog failing, as well.

Share:
5,846

Related videos on Youtube

fred basset
Author by

fred basset

Engineer working with C, C++, assembler and embedded hardware.

Updated on September 18, 2022

Comments

  • fred basset
    fred basset over 1 year

    The hardware watchdog on my system needs a 0 written to /dev/watchdog at less than 60 seconds interval or it will fire. The file handle must be kept open however or the watchdog is then disabled.

    E.g.

    echo "0" > /dev/watchdog
    

    does not work, as the file handle is closed after the echo is completed.

    Is there any way to setup a loop in bash that will write 0 periodically to /dev/watchdog but keep the file handle open?

  • Stéphane Chazelas
    Stéphane Chazelas almost 10 years
    That's the whole point of the watchdog: trigger something when the writer fails to reset it.
  • clerksx
    clerksx almost 10 years
    @StéphaneChazelas I'm not sure which part of my answer you are responding to. Presumably, if the watchdog is enabled, the watchdog has some reason to be so. A condition to check the real reason the watchdog is enabled should ideally be performed instead of just resetting the watchdog. If there's no reason to run the watchdog, it might as well be disabled instead.
  • ninjalj
    ninjalj almost 10 years
    @ChrisDown: in this case, it protects against hardware lockups, and some kinds of kernel lockups (on SMP you can have a CPU locked up and still be running on the others).