为什么`timeout`不适用于管道?

问题描述:

下面的timeout命令行调用(仅出于测试原因没有意义)无法按预期方式工作.它等待10秒钟,并且3秒钟后不停止命令的运行.为什么?

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

您的命令正在运行timeout 3 ls,并将其输出传递到sleep 10.因此,sleep命令不受timeout的控制,它将始终睡眠10秒钟.

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"