BreezyChick89
BreezyChick89

Reputation: 1479

Should I bother closing a socket connection if the Pid is about to die?

When a Pid dies it frees all file handles/ports that are associated with it. If the process is about to die should I bother calling something like gen_tcp:close or ssl:close even if it's the last thing it does?

Upvotes: 5

Views: 673

Answers (1)

cegfault
cegfault

Reputation: 6632

By "should I bother" do you mean, "will I risk a memory leak?", or "could it result in data loss?", or "does it affect how the client sees and closes the connection?"

That being said, it is considered polite to issue the close command, for the client's sake. The client might see an abrupt break in the connection instead of a close. For example, if it's a web server, and you do not send the close, then certain browsers will read it as an pipe break (error) and immediately try to reconnect. Closing the connection properly is just polite, and it will help keep your code organized logically (you know exactly how all of your resources get handled).

I'm not 100% sure how erlang handles garbage collection, but I can say that for most programming languages (and thereby I'm assuming erlang as well), killing the process will take care of all of the memory associated with it, so there should be no memory leak in just letting the process die.

If, however, there is potential content left in a buffer to be sent to the client, you may want to make your exit procedure such that it flushes the buffer or connection before it closes, otherwise you might risk data loss.

Edit: as legoscia mentioned, any open file descriptors should be handled gracefully by erlang, but it never hurts (and I would call it "good practice") to close them yourself before exiting the process.

Upvotes: 8

Related Questions