Timeout / early kill an external process

I want to do a terminal command (on linux) with a timeout. I know there is not a timeout built into the run command so I was trying to do something to make one. So basically I tried:

function run_with_timeout(command::String, timeout::Integer = 5)
    cmd = run(`$command`; wait = false) 
     for i in 1:timeout 
         if success(cmd) return :success end 
         sleep(1)
     end
     kill(cmd) 
     return :failed
end
command = "sleep 3"
run_with_timeout(command)

This doesn’t work because success(cmd) waits until the process finishes rather than immediately saying whether or not the process has finished yet.

Is there a function that immediately says whether or not a process is finished yet? Any other way to achieve this goal?

Can you call istaskdone on the cmd?

it’s called process_running for run() (which creates process with some pid)

julia> function run_with_timeout(command, timeout::Integer = 5)
           cmd = run(command; wait=false)
            for i in 1:timeout
                if !process_running(cmd) return success(cmd) end
                sleep(1)
            end
            kill(cmd)
            return false
       end

julia> @time run_with_timeout(`sleep 7`)
  5.010722 seconds (48 allocations: 2.062 KiB)
false

julia> @time run_with_timeout(`sleep 2`)
  2.003042 seconds (37 allocations: 1.703 KiB)
true

btw I changed your function to return a boolean instead of symbol, and also to return false in case where cmd finished running with an error

3 Likes