Alexander Hades
Alexander Hades

Reputation: 113

Erlang OTP supervisor gen_tcp - {error,eaddrinuse}

I'm failing to see how adding a supervisor to a crashing gen_tcp:listen-thread would actually restart that worker. Since crashing would render the port I wanna listen on useless for a brief moment. When a crash occur and I'm trying to manually restart my application I receive "{error,eaddrinuse}". I haven't implemented any supervisor for this worker yet since I fail to see how it would work.

How do I restart a gen_tcp:listen?

Upvotes: 3

Views: 2488

Answers (2)

Paul Guyot
Paul Guyot

Reputation: 6347

In most cases, as the listen socket is linked to the controlling process (the process that created it), a termination of this process will close the socket nicely and allow you to listen again on the same port.

For all other cases, you should pass {reuseaddr, true} option to gen_tcp:listen/2. Indeed, the listen socket of your application remains active for a brief moment after a crash, and this option allows you to reuse the address during this period.

Upvotes: 2

Soup in Boots
Soup in Boots

Reputation: 2392

Is the process managing the gen_tcp socket a gen_server? If so, it will make your life easier.

If it is a gen_server, add process_flag(trap_exit, true) to your init function. This makes it so that when your process "crashes", it calls the terminate/2 callback function prior to actually exiting the process. Using this method, you can manually close your listening socket in the terminate function, thereby avoiding the irritating port cleanup delay.

If you are not using a gen_server, the same principle still applies, but you must be much more explicit about catching your errors.

Upvotes: 1

Related Questions