tags:

views:

63

answers:

1

Is there a way to get a registered name if you have a PID?

+4  A: 

I'm assuming you want this for some kind of debugging/introspection purpose and not for general use in your code:

erlang:process_info(Pid, registered_name).

Gives you [] if the process doesn't have a locally registered name, and {registered_name, Name} if there is one.

archaelus
You can also use: proplists:get_value(registered_name,erlang:process_info(Pid)). Returns the name straight away or the atom undefined. Same concept though.
Mazen Harake
The purpose: I have a gen_server which serves as the main behavior for a set of processes. However, each process needs to have some supplemental behaviors that I supply with a sort of "callback" module. When the supervisor starts, it will make several copies of the main gen_server, registering each under a different name. These different names will also be the name of the callback modules. I could also pass in the callback module as an argument, but why bother if it's already available with a call. Or is there a cleaner idea?
mwt
Passing information by reading the processes own registered name is going to be deeply confusing for people used to more typical erlang code - if you want that information available, pass it explicitly and store it in the #state{} record. There are all sorts of cunning mechanisms you can use to pass information around (process dictionary, parametrized modules and the like), but I'd recommend against it because it makes the code harder to follow. It's nice in Erlang being able to work out the effect of a function just by looking at its code and the arguments it is given.
archaelus