Title says it all. How can I handle or catch a SIGINT
in julia? From the docs I assumed I just wanted to catch InterruptException
using a try/catch
block like the following
try
while true
println("go go go")
end
catch ex
println("caught something")
if isa(ex, InterruptException)
println("it was an interrupt")
end
end
But I never enter the catch block when I kill the program with ^C
.
edit: The code above works as expected from the julia REPL, just not in a script.
I see the same behavior as alto, namely that SIGINT
kills the entire process when my code is run as a script but that it is caught as an error when run in the REPL. My version is quite up to date and looks rather similar to that of tholy:
julia> versioninfo()
Julia Version 0.3.7
Commit cb9bcae* (2015-03-23 21:36 UTC)
Platform Info:
System: Linux (x86_64-linux-gnu)
CPU: Intel(R) Core(TM) i7-3610QM CPU @ 2.30GHz
WORD_SIZE: 64
BLAS: libopenblas (DYNAMIC_ARCH NO_AFFINITY Sandybridge)
LAPACK: libopenblas
LIBM: libopenlibm
LLVM: libLLVM-3.3
Digging through the source, I found hints that Julia's
interrupt behavior is determined by an jl_exit_on_sigint
option, which can be set via a ccall
. jl_exit_on_sigint
is 0
for the REPL, but it looks as if init.c
sets it to 1
when running a Julia
program file from the command line.
Adding the appropriate ccall
makes alto's code works regardless of the calling environment:
ccall(:jl_exit_on_sigint, Void, (Cint,), 0)
try
while true
println("go go go")
end
catch ex
println("caught something")
if isa(ex, InterruptException)
println("it was an interrupt")
end
end
This does seem to be a bit of a hack. Is there a more elegant way of selecting the interrupt behavior of the environment? The default seems quite sensible, but perhaps there should be a command line option to override it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With