【问题标题】:why does `timeout 2 timeout 1 bash` stuck为什么`timeout 2 timeout 1 bash`卡住了
【发布时间】:2023-04-04 20:42:01
【问题描述】:

我正在研究 Linux shell 中的timeout 命令。

当我尝试timeout 1 bash 时,bash 将运行并在 1 秒后被杀死。

当我尝试timeout 2 timeout 1 yes 时,程序yes 将运行1 秒并被第二个timeout 杀死。

但是当我尝试timeout 2 timeout 1 bash 时,它卡住了。没有 bash shell 出现,即使我按 Ctrl+C 也会继续运行。

我知道在一个命令中写两个timeout是没有用的。

我只是想知道为什么会发生这种情况。

【问题讨论】:

  • 确实很有趣。我用其他shell(fish,zsh)尝试过它,它起作用了。使用 bash,如果您使用 -k 调用外部超时,它就会起作用,即timeout -k 3 2 timeout 1 bash。我不知道 bash 做了什么这么特别,以至于外部超时命令会受到影响。

标签: linux bash shell timeout signals


【解决方案1】:

这是相同行为的另一个示例:

strace timeout 1 bash 即使你中断了 strace,bash 也会继续运行。

如果我们同时 strace bash 进程本身,我们会注意到以下循环。

--- SIGTTIN {si_signo=SIGTTIN, si_code=SI_USER, si_pid=7162, si_uid=1000} --- rt_sigaction(SIGTTIN, {sa_handler=SIG_IGN, sa_mask=[],sa_flags=SA_RESTORER,sa_restorer=0x7f097723a7e0}, {sa_handler=SIG_DFL,sa_mask=[],sa_flags=SA_RESTORER, sa_restorer=0x7f097723a7e0}, 8) = 0 ioctl(255, TIOCGPGRP, [6412])
= 0 rt_sigaction(SIGTTIN,{sa_handler=SIG_DFL,sa_mask=[],sa_flags=SA_RESTORER,sa_restorer=0x7f097723a7e0}, {sa_handler=SIG_IGN, sa_mask=[], sa_flags=SA_RESTORER, sa_restorer=0x7f097723a7e0}, 8) = 0 杀 (0, SIGTTIN) = 0

现在,根据http://www.gnu.org/software/libc/manual/html_node/Job-Control-Signals.html

宏:int SIGTTIN

进程在作为后台作业运行时无法从用户终端读取。当后台作业中的任何进程尝试 从终端读取,作业中的所有进程都被发送一个 SIGTTIN 信号。此信号的默认操作是停止 过程。有关它如何与 终端驱动程序,请参阅访问终端。

timeout 2 timeout --foreground 1 bash 有效,因为内部超时将允许它与 tty 一起工作,尽管它不是直接从交互式 shell 运行的。

人工超时

   --foreground

          when not running timeout directly from a shell prompt,

          allow COMMAND to read from the TTY and get TTY signals; in this mode, children of COMMAND will not be timed out

我们可以链接任意数量的超时,只要除了从交互式 shell 运行的所有超时都使用 --foreground 选项:

timeout 3 timeout --foreground 2 timeout --foreground 1 bash

另请查看man bash 中的SIGNALS 部分,了解有关 bash 在不同情况下如何对各种信号作出反应的更多信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-14
    • 2011-09-13
    • 2012-07-11
    • 2011-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多