Shell 程序只是打开一个字符驱动程序并等待

yas*_*shC 5 linux bash shell-script

启发这个问题的是我正在测试看门狗设备的功能,我在想是否有一个 shell 内置命令来打开设备并且什么都不做/等到终止? Echo/touch似乎只是在执行操作后立即打开和关闭设备。Cat似乎不起作用。

我正在使用 C 应用程序来做同样的事情,但想知道 shell 脚本是否有一些规定

Sté*_*las 12

在类似伯恩的贝壳中,

exec 3< "$device"
Run Code Online (Sandbox Code Playgroud)

在 shell 的文件描述符 3 上打开设备。

这或多或少相当于 C 的:

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

ksh93也在fcntl(3, F_SETFD, FD_CLOEXEC)那个 fd 上做了一个)。

要关闭它: exec 3<&-

zsh,ksh93和 中bash, 的等价物fd = open(device, O_RDONLY)也可以写成:

exec {fd}< "$device"
Run Code Online (Sandbox Code Playgroud)

其中文件描述符将是第一个大于 9 的空闲描述符并存储在$fd.

要关闭它: exec {fd}<&-

替换<>for O_WRONLY|O_CREAT|O_TRUNC,并替换为<>forO_RDWR|O_CREAT>>for O_WRONLY|O_CREAT|O_APPEND

zsh也有一个sysopen内置(在zsh/system模块中),您可以在其中准确指定标志。

请注意,在符合 POSIX 的 shell 中,exec作为一个特殊的 builtin,如果无法打开文件,则在非交互式(它退出脚本)时会出现致命错误。您可以使用该command命令禁用它。

if command exec 3< "$device"; then
  do-what-you-need-to-do
else
  handle-the-error-yourself
fi
Run Code Online (Sandbox Code Playgroud)