문제

My original problem was to kill a process & its children when timeout. And I found GNU timeout quite a good choice.

However, in this testcase, things become weird:

Assume that we have a test1.sh like this:

#!/bin/sh
# test1.sh
output=`timeout 2 ./run.sh`
echo $output

and run.sh like this:

#!/bin/sh
# run.sh
sleep 8s&

Intuitively we should expect test1.sh exits instantly, since init will take charge of that silly sleep process and run.sh will then exits.

However:

sh-4.2$ time ./test1.sh

real    0m8.022s
user    0m0.013s
sys     0m0.003s

And if I create this test2.sh:

#!/bin/sh
# test2.sh
timeout 2 ./run.sh
sh-4.2$ time ./test2.sh

real    0m0.014s
user    0m0.003s
sys     0m0.007s

So, obviously we hit something wrong during command substitution, but why?

도움이 되었습니까?

해결책

It may be the way you have in shell script --

`timeout 2 ./run.sh` 

-- you are using command substitution, so as long as the command has not finished execution, substitution cannot be done, because the output is not there...this may explain the output you are seeing.

Try this to see a similar outcome....

echo "hello `sleep 2 &`"

Another script of interest --

$ cat y.sh
echo "hi"
sleep 2 &
echo "bye"
sleep 2 &

Run using

echo "hello `sh y.sh`"

$time sh y.sh
hi
bye

real    0m0.006s
user    0m0.000s
sys     0m0.004s

$time echo "hello `sh y.sh`"
hello hi
bye

real    0m2.008s
user    0m0.004s
sys     0m0.000s

This page explains more about the relationship between background process and file descriptor. Basicly:

Background (better: forked) processes inherit the file descriptors, and Running a command in backticks means to collect its stdout until its stdout is closed

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top