Home » Questions » Computers [ Ask a new question ]

How Do You Determine The PID of the Parent of a Process

How Do You Determine The PID of the Parent of a Process

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?

Asked by: Guest | Views: 64
Total answers/comments: 4
Guest [Entry]

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

spawn_link(?MODULE, child, [self()])."
Guest [Entry]

@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.
Guest [Entry]

"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."
Guest [Entry]

"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."