bash 为什么“超时”不适用于管道?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11943104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 03:00:58  来源:igfitidea点击:

Why does `timeout` not work with pipes?

bashtimeoutpipe

提问by John Threepwood

The following command line call of timeout(which makes no sense, just for testing reason) does not work as expected. It waits 10 seconds and does not stop the command from working after 3 seconds. Why ?

以下命令行调用timeout(毫无意义,仅用于测试原因)无法按预期工作。它等待 10 秒,并且在 3 秒后不会停止命令的工作。为什么 ?

timeout 3 ls | sleep 10

回答by Shawn Chin

What your command is doing is running timeout 3 lsand piping its output to sleep 10. The sleepcommand is therefore not under the control of timeoutand will always sleep for 10s.

您的命令正在运行timeout 3 ls并将其输出通过管道传输到sleep 10. sleep因此该命令不受控制,timeout并且将始终休眠 10 秒。

Something like this would give the desired effect.

像这样的东西会产生预期的效果。

timeout 3 bash -c "ls | sleep 10"

回答by mjgpy3

The 'ls' command shouldn't be taking 3 seconds to run. What I think is happening is you are saying (1) timeout on ls after 3 seconds (again this isn't happening since ls shouldn't take anywhere near 3 seconds to run), then (2) pipe the results into sleep 10 which does not need further arguments than the number you are giving it. Thus ls happens, timeout doesn't matter, and bash sleeps for 10 seconds.

'ls' 命令不应花费 3 秒来运行。我认为正在发生的事情是您说 (1) 3 秒后 ls 超时(这再次不会发生,因为 ls 不应该花费接近 3 秒的时间来运行),然后 (2) 将结果输入 sleep 10不需要比您提供的数字更多的参数。因此 ls 发生,超时无关紧要,bash 休眠 10 秒。

回答by Thor

The only way I know how to get the effect you're after, is to put the piped commands into a separate file:

我知道如何获得您想要的效果的唯一方法是将管道命令放入一个单独的文件中:

cat > script
ls | sleep 10
^D

timeout 3 sh script

回答by Kombajn zbo?owy

It is enough to set the timeout on the lastcommand of the pipeline:

在管道的最后一个命令上设置超时就足够了:

# Exits after 3 seconds with code 124
ls | timeout 3 sleep 10

# Exits after 1 second with code 0
ls | timeout 3 sleep 1