How to make TCP socket listening more robust to errors?

I’ve written a simple package for evaluating functions and passing data between Julia processes using TCP sockets.

It works pretty well, as long as the function evaluations don’t produce any errors. If the an error occurs, it won’t be printed and the listening socket breaks and needs to be restarted. The try/catch code I added doesn’t seem to be helping (no errors are ever caught).

Simplified version of the listening code:

function ipc_listen(addr::Sockets.InetAddr)
 server = Sockets.listen(addr)
 @async begin
  socket = Sockets.accept(server)
  while true
   try
    fun = Serialization.deserialize(socket)
    args = Serialization.deserialize(socket)
    @eval(Main, $fun($args...))
   catch e
    println(STDERR, e)
   end
 end
 server
end

Full code is here:

The problem is that errors in an @async block are just swallowed if you leave the block dangling into nothing like that. You can either wait on the async block. Or you can do something similar to this code from my Animations package, where I tried to solve the same problem. I mostly copied it from some other thread once, but don’t remember which one…

macro async_showerr(ex)
    quote
        t = @async try
            eval($(esc(ex)))
        catch err
            bt = catch_backtrace()
            println("Asynchronous animation errored:")
            showerror(stderr, err, bt)
        end
    end
end
@async_showerr while true
    # do stuff
end
1 Like