gproc icon indicating copy to clipboard operation
gproc copied to clipboard

Can I reg another pid?

Open klajo opened this issue 9 years ago • 3 comments

Hi,

I have a message based interface. One of the messages is a subscribe operation and I want to implement the subscription service on the "server side" (the one keeping track of the subscriptions). I thought I'd use gproc for this, but I can find no way of subscribing some other process than myself.

I'm looking for something like erlang:register/2 with the extra pid argument.

Is there something like that available that I haven't found?

(I still want the semantics of having gproc monitor that process for cleanup purposes)

Cheers, Klas

klajo avatar Oct 27 '15 15:10 klajo

I was going to write another explanation for why this functionality was excluded in the first place, but then decided that some of those reasons are invalid, and others are a matter of taste. I've added a warning to the documentation, strongly recommending that processes should register only their own resources.

Two simple test cases added - one for the local and one for the distributed case. Please give feedback.

uwiger avatar Oct 27 '15 18:10 uwiger

Hi,

Thanks for the quick response. Maybe gproc is not the tool for this task. Regarding the ownership (having processes register their own resources), I agree. In this case the subscribe message is outside of my control though.

Ideally I'd want a p-key like {l, p, foo} and saw your note about that.

Again, thanks for the quick support.

klajo avatar Oct 28 '15 12:10 klajo

If the other process properly handles system messages, there is a way to execute code inside the other process: sys:replace_state/2 (since OTP R16B). The function is only intended for debugging, according to the documentation.

A subscription function might then look like (NOTE: not tested):

subscribe(Pid, Scope, Event) ->
    if Pid == self() ->
        gproc_ps:subscribe(Scope, Event);
    true ->
        sys:replace_state(Pid, fun(S) -> gproc_ps:subscribe(Scope, Event), S end)
    end.

The sys:replace_state/2 function has a 5-second timeout by default.

(Actually, in the original gproc paper, chapter 9.1, I suggested an extension to sys.erl to this effect. I will have words over beer with @vinoski for not mentioning this in his OTP commit)

uwiger avatar Oct 28 '15 15:10 uwiger