Erlang:如何只接收来自特定发件人的消息?

Erlang: How to receive a message only from a specific sender?

在 Erlang 中,如何接收来自特定 pid 的消息?

您需要在消息中包含发件人的 pid,并在接收过程中与之匹配。

这里有几种方法:

1) 向目标进程发送一个密码,它可以将其与所有消息一起发回:

-module(my).
-compile(export_all).

worker(TargetPid, Msg, SecretId) ->
     TargetPid ! {Msg, SecretId}.

get_msg(SecretId) ->
    receive
        {Msg, SecretId} -> Msg
    end. 

test() ->
    SecretId = "A1!cd!",
    spawn(my, worker, [self(), hello, "Xy*d1"]),
    spawn(my, worker, [self(), goodbye, SecretId]),

    io:format("~w~n", [get_msg(SecretId)]).

在shell中:

6> c(my).    
my.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,my}

7> my:test().
goodbye
ok

8> 

2) 让目标进程发送一条标有其 Pid 的消息,而不是与接收子句中的密码进行匹配:

-module(my).
-compile(export_all).

get_msg(TargetPid) ->
    receive
        {Msg, TargetPid} -> Msg
    end. 

worker(TargetPid, Msg) ->
     TargetPid ! {Msg, self()}.

test() ->
    spawn(my, worker, [self(), hello]),
    Pid = spawn(my, worker, [self(), goodbye]),

    io:format("~w~n", [get_msg(Pid)]).

在shell中:

3> c(my).
my.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,my}

4> my:test().
goodbye
ok

5>