Skip to content

Instantly share code, notes, and snippets.

@ericphanson
Created January 20, 2022 03:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericphanson/e5864b6d1aa15e8f4235ce0e6e126a1e to your computer and use it in GitHub Desktop.
Save ericphanson/e5864b6d1aa15e8f4235ce0e6e126a1e to your computer and use it in GitHub Desktop.
Julia script to run processes with 2 second timeout
❯ ./timeout.jl ps
PID TTY TIME CMD
697 ttys000 0:00.16 -zsh
1132 ttys001 0:00.09 /bin/zsh --login
3115 ttys002 0:00.09 /bin/zsh -l
3632 ttys003 0:00.32 /bin/zsh -l
11816 ttys003 0:00.32 /Users/eph/.asdf/installs/julia/1.7.1/bin/julia --color=yes --startup-file=no -O0 --compile=min ./timeout.jl ps
❯ ./timeout.jl sleep 3 && echo "done"
❯ ./timeout.jl sleep 1 && echo "done"
done
#!/bin/bash
#=
exec julia --color=yes --startup-file=no -O0 --compile=min "${BASH_SOURCE[0]}" "$@"
=#
function trykill(p, n=Base.SIGTERM)
try
kill(p, n)
true
catch e
false
end
end
out = PipeBuffer()
err = PipeBuffer()
p = run(pipeline(`$ARGS`, stdout=out, stderr=err), wait=false)
result = timedwait(() -> !process_running(p), 2) # 2 is the time in seconds to wait
if result == :timed_out
success = trykill(p)
success && exit(1)
success = trykill(p, Base.SIGKILL)
success && exit(1)
error("Zombie! Could not kill process with pid $(getpid(p))")
else
write(stdout, take!(out))
write(stderr, take!(err))
exit(0)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment