linux kill process using timeout in milliseconds

笑着哭i 提交于 2019-12-13 21:20:10

问题


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


来源:https://stackoverflow.com/questions/16422740/linux-kill-process-using-timeout-in-milliseconds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!