Search code examples
linuxshelltimeoutkillterminate

linux kill process using timeout in milliseconds


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.


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