Question

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.

Was it helpful?

Solution

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 

OTHER TIPS

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

You can use a function, accept millisecond values

timeout_m ()
{
  $2 &
  for (( y=0; y<$1*50; y++ ))
  do
    :
  done
  kill $!
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top