Setting Timeout and C-C capture

dear Julia wizards—I want to create julia code segments that recognize (and trap) a control-C; and I want to create julia code that times out. my julia code segments may be trying to obtain something from the host computer or from the network.

Trapping C-C

julia> ## enable trapping of ^C.  ccall( :jl_exit_on_sigint, Nothing, (Cint,), 0 ) fails

julia> try
	    ticks= 0
	    while true
	        sleep(0.5)
	        ticks += 1
	        println( "Please type ^C now ($ticks)" )
	    end##while##
       finally
	    println("OK, we are breaking out!")
       end##try##

julia> println("Freedom!")	## is not reached, because ^C stops execution after try

julia> ## restore standard ^C behavior

Setting Timeout

I know how to do this in perl, but not in Julia. In perl

   eval {
        local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
        alarm $timeout;
        my $nread = sysread $socket, $buffer, $size;	## an example of a function where we do not know if it will work
        alarm 0;
    };
    if ($@) {
        die unless $@ eq "alarm\n";   # propagate unexpected errors
        # timed out
    }
    else {
        # didn't
    }

Does anyone have working examples?

regards,

/iaw

In Julia ctrl-C throws an InterruptException, so you should just be able to do something like

try
    # code that might take a while, e.g.
    sleep(10)
catch ex
    if ex isa InterruptException
        println("we got interrupted")
    else
        rethrow()
    end
end

That said, I just tested this on my Windows box and it actually waits until the sleep call completes before throwing the exception, which is weird.

1 Like

thanks, ssfr. on macos, this code works! now all I need is the alarm/timeout ;-).