linux kill process using timeout in milliseconds

2019-08-27 21:32发布

问题:

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 $!
}