linux kill进程使用超时(以毫秒为单位)

时间:2013-05-07 15:20:50

标签: linux shell timeout kill terminate

我希望在linux上经过指定的时间后强制终止程序。 我发现linux中的'timeout'util可以在指定的时间后杀死一个程序, 但它不接受MILLISECONDS。 也就是说,“TIME TIME ./PROGRAM”在TIME过去之后杀死PROGRAM,其中TIME不是毫秒而是秒。 在Linux SHELL 上的一些MILLISECONDS之后有没有办法杀死进程? 任何意见将不胜感激。

3 个答案:

答案 0 :(得分:4)

您可以这样做:

#!/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 

答案 1 :(得分:2)

最新版本的超时实际上也支持毫秒。您可以将等待时间作为浮点数提供。例如

$timeout 0.003s sleep 0.003 && echo foo
$

,而

$ timeout 0.003s sleep 0.001 && echo foo
foo

答案 2 :(得分:-1)

您可以使用函数,接受毫秒值

timeout_m ()
{
  $2 &
  for (( y=0; y<$1*50; y++ ))
  do
    :
  done
  kill $!
}