5

What inspired this question is that I am testing the functionality of watchdog device and I was thinking if there is a shell inbuilt command to just open the device and do nothing/wait until terminated? Echo/touch seem to just open and close the device immediately after performing the operation. Cat does not seem to work.

I am using a C application to do the same but was wondering if shell script has some provision for it

12

In Bourne-like shells,

exec 3< "$device"

Opens the device on file descriptor 3 of the shell.

That would be more or less equivalent to C's:

fd = open(device, O_RDONLY);
if (fd < 0) handler_error(...);
if (fd != 3) { dup2(fd, 3); close(fd); }

(ksh93 also does a fcntl(3, F_SETFD, FD_CLOEXEC) on that fd).

To close it: exec 3<&-

In zsh, ksh93 and bash, the equivalent of fd = open(device, O_RDONLY) could also be written as:

exec {fd}< "$device"

Where the file descriptor would be the first free one above 9 and stored in $fd.

To close it: exec {fd}<&-

Replace < with > for O_WRONLY|O_CREAT|O_TRUNC, and with <> for O_RDWR|O_CREAT and >> for O_WRONLY|O_CREAT|O_APPEND.

zsh also has a sysopen builtin (in the zsh/system module) where you can specify the flags exactly.

Note that in POSIX compliant shells, exec being a special builtin, if the file can't be opened, it's a fatal error when non-interactive (it exits the script). You can disabled that by using the command command.

if command exec 3< "$device"; then
  do-what-you-need-to-do
else
  handle-the-error-yourself
fi
2
while sleep 3600; do :; done >/dev/your_watchdog

I gather (from the echo and touch working and the cat failing) that the device should be open in write only mode.

  • sleep 1e99 >/dev/your_watchdog would also work, assuming you're not planning on being after 10 to the 91 years or so... – Digital Trauma Dec 10 '18 at 20:38
  • sleep: invalid number '1e99' ;-) – pizdelect Dec 11 '18 at 2:03

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.