Timeout / early kill an external process

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

4 Likes