Search code examples
erlangrestarterlang-otperlang-supervisorgen-tcp

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?


Solution

  • 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.