I want to force terminate a program after a specified time is elapsed on linux. I found that 'timeout' util in linux can kill a program after a specified time, but it does not accept MILLISECONDS. That is, "timeout TIME ./PROGRAM" kills PROGRAM after TIME elapsed where TIME is not milliseconds but seconds. Is there a way to kill a process after some MILLISECONDS on linux SHELL? Any comments would be appreciated.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
You can do something like this:
#!/bin/bash
#execute command in background
<command> &
#get process ID
PROC=$!
#sleep for 10 milliseconds then kill command
(usleep 10000; kill $PROC) &
#bring back the process ID, finish command or kill it
fg $PROC
回答2:
The latest version of timeout actually supports milliseconds as well. You can supply the waiting time as a floating point number. For example
$timeout 0.003s sleep 0.003 && echo foo
$
while
$ timeout 0.003s sleep 0.001 && echo foo
foo
回答3:
You can use a function, accept millisecond values
timeout_m ()
{
$2 &
for (( y=0; y<$1*50; y++ ))
do
:
done
kill $!
}