1

Is it possible to catch a SIGINT to stop a Julia program from running, but doing so in an "orderly" fashion?

function many_calc(number)
    terminated_by_sigint = false
    a = rand(number)
    where_are_we = 0
    for i in eachindex(a)
        where_are_we = i
        # do something slow...
        sleep(1)
        a[i] += rand()
    end
    a, where_are_we, terminated_by_sigint
end

many_calc(100)

Say I want to end it efter 30 seconds, because I didn't realize it would take so long, but don't want to throw away all the results, because I have another method to continue from where_are_we-1. Is it at all possible to stop it (softly) early, but using the SIGINT signal?

pkofod
  • 764
  • 7
  • 18

1 Answers1

2

You can just use a try ... catch ... end and check if the error is an interrupt.

For your code:

function many_calc(number)
    terminated_by_sigint = false
    a = rand(number)
    where_are_we = 0
    try

        for i in eachindex(a)
            where_are_we = i
            # do something slow...
            sleep(1)
            a[i] += rand()
        end

    catch my_exception
        isa(my_exception, InterruptException) ? (return a, where_are_we, true) : error()
    end

    a, where_are_we, terminated_by_sigint
end

Will check if the exception is an interupt, and will return with the values if so. Else it will error.

Alexander Morley
  • 4,111
  • 12
  • 26