tags:

views:

97

answers:

3

Is it allowed to have one process reading from and another process writing to a socket in Erlang? I have tried it and it appears to work but I would like to know if it's foolproof.

+1  A: 

I am pretty sure I remember doing this without any problems.

jldupont
+2  A: 

As I understand it from the source code, a (gen_tcp, at least) socket send/recv boils down to an erlang:port_command for the send and an erlang:port_control for the recv on the socket port (see prim_inet.erl).

For port_command: "if the port is busy, the calling process will be suspended until the port is not busy anymore." The port_control is also a synchronous operation.

Correct me if I'm wrong, but it would appear to be completely safe to use multiple processes to read and write to a socket.

MatthewToday
One comment though, is that if the "owning" process dies then the socket will close. So it's not symmetric usage between the two processes.
Daniel Luna
+1  A: 

Anyone of them can write, but it wouldn't make sense if all your processes could receive. It would overflow the mailboxes of all the ones not anticipating messages. You need to define only one Pid to receive packets, by default it's whatever Pid the socket was created in. You can set any Pid to control the socket by setting the controlling process.

Jimmy Ruska
What if you use {active, false} and recv() to get data from the socket? While I don't know for sure, I would expect that several processes could each call recv(), and this would work fine.
Daniel Yankowsky
This is true. It's hard for me to imagine passing around sockets where different processes call recv though. Better to make active and have a dedicated loop receiving {tcp,Sock,Data}. Least that's how I'm used to working with them.
Jimmy Ruska