attdona
attdona

Reputation: 18923

How to capture linux signals in julia

I'm looking for a way to capture SIGINT in a julia script on a linux host, but I'm not able to understand how to manage signals.

In the REPL:

julia > try
    sleep(1000)
catch e
    @info "interrupt captured!"
end
Ctrl-C
[ Info: interrupt captured!

Instead, executing demo.jl:

try
    sleep(1000)
catch e
    @info "interrupt captured!"
end

gives:

terminal> julia demo.jl
Ctrl-C

signal (2): Interrupt
in expression starting at /tmp/demo.jl:3
epoll_pwait at /lib/x86_64-linux-gnu/libc.so.6 (unknown line)
uv__io_poll at /workspace/srcdir/libuv/src/unix/linux-core.c:270
uv_run at /workspace/srcdir/libuv/src/unix/core.c:359
jl_task_get_next at /buildworker/worker/package_linux64/build/src/partr.c:473
poptask at ./task.jl:704
wait at ./task.jl:712 [inlined]
...

How to manage the interrupt in this case?

Upvotes: 4

Views: 560

Answers (2)

iclac
iclac

Reputation: 106

As described here InterruptException is not thrown by Ctrl-C when you exec julia demo.jl. Use instead:

Base.exit_on_sigint(false)

try
   while true
      sleep(1)
      @info "."
   end
catch e
   @info "interrupt captured!"
end

And I think sleep(1000) isn't helpful in this context.

Upvotes: 5

user12196313
user12196313

Reputation:

I would not use exceptions if you want to just catch the SIGINT signal, i would set an handler. You should take a look at the atexit(f) function.

atexit() do
    
   //Handle your exception here if necessary

end

EDIT: Try this way if the first doesn't works:

atexit(exitFunc()

      //Code to be executed when the signal is received

end)

Upvotes: 0

Related Questions