Why does `timeout` not work with pipes?

|▌冷眼眸甩不掉的悲伤 提交于 2020-04-06 08:28:21

问题


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 3 ls | sleep 10

回答1:


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

Something like this would give the desired effect.

timeout 3 bash -c "ls | sleep 10"



回答2:


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.




回答3:


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



回答4:


It is enough to set the timeout on the last command 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


来源:https://stackoverflow.com/questions/11943104/why-does-timeout-not-work-with-pipes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!