Killing processes in Erlang by PIDs
I am implementing a chat server in Erlang. According to my design, each client has a corresponding agent process on the server node that handles the messages. I am writing the PIDs of the agents into database so that I can exchange messages between them.
Is it safe when I kill the PIDs? For example, after my server restarts, the PIDs are still in the database (but the processes will die), will there be chances that the PIDs in the database clash with some other (newly created) important processes?
If so I c开发者_如何学Goannot simply kill the agent when the client is not responding. So far, I have not observed it, but it would be nice to know for sure.
PIDs are assigned in spawn order from 0.0.0 (init) every time the node is started. So yes, you can easily get PID collisions if you save them between node restarts.
You've built some kind of registry to allow you to look up the PID for a particular client - this registry needs to remove dead PIDs in a timely manner. A typical design is for the registry to monitor (erlang:monitor/2
) each registered process and remove the registry entry when the process dies and the {'DOWN', Ref, process, Pid, Info}
message is received.
I would also add that storing a PID outside erlang (if your database is not ets or mnesia) is unusual for this reason - the PID won't mean anything after the process or node dies.
PIDs can be re-used across restarts. It's very likely that they will collide with other PIDs because they are sequential. You should make sure to clear out any PID from your database that corresponds to a node that has gone down.
1> spawn(fun () -> ok end).
<0.35.0>
2> spawn(fun () -> ok end).
<0.37.0>
3> spawn(fun () -> ok end).
<0.39.0>
精彩评论