tags:

views:

455

answers:

4

I have a process in erlang that is supposed to do something immediately after spawn, then send the result back to the parent when it is finished. How do I figure out the PID of the process that spawned it?

+11  A: 

You should pass self() to the child as one of the arguments to the entry function.

spawn_link(?MODULE, child, [self()]).
Kevin Ballard
A: 

You can use the BIF register to give the spawning / parent process a name (an atom) then refer back to the registered name from other processes.

FUNC() ->

%% Do something
%% Then send message to parent
parent ! MESSAGE.

...

register(parent, self()),
spawn(MODULE, FUNC, [ARGS]).

See Getting Started With Erlang §3.3 and The Erlang Reference Manual §10.3.

Greg Case
While you could do it by registering a name, it is not at all a good idea. This post would be better if you actively discouraged for doing it and explained the problems.
Christian
Back in the private beta (this question dates back to about a week after the private beta began) the discussion aspect of the site was not terribly well-formed. I didn't really want to state an opinion, merely state an alternative approach. I think the pros and cons have been adequately addressed in the other answers / posts.
Greg Case
+4  A: 

@Eridius' answer is the preferred way to do it. Requiring a process to register a name may have unintended side-effects such as increasing the visibility of the process not to mention the hassle of coming up with unique names when you have lots of processes.

+2  A: 

The best way is definitely to pass it as an argument to the function called to start the child process. If you are spawning funs, which generally is a Good Thing to do, be careful of doing:

spawn_link(fun () -> child(self()) end)

which will NOT do as you intended. (Hint: when is self() called)

Generally you should avoid registering a process, i.e. giving it a global name, unless you really want it to be globally known. Spawning a fun means that you don't have to export the spawned function as you should generally avoid exporting functions that aren't meant to be called from other modules.

rvirding