[erlang-questions] spawn_link

John Hughes john.hughes@REDACTED
Mon Dec 29 17:39:21 CET 2008


Hi Thilani,

As Chandru said, you just send the result back to the parent process as a 
message. Here's some code:

spawn_call(M,F,As) ->
    Parent = self(),
    Child = spawn_link(fun() -> Parent ! {self(),apply(M,F,As)} end),
    receive {Child,X} -> X end.

Note the receive matches on the child's pid, so can't be confused by any 
other messages in the parent's mailbox. Sample call:

76> foo:spawn_call(lists,reverse,[[1,2,3]]).
[3,2,1]

John

> From: "Thilani Abeysinghe" <a.thilani@REDACTED>
> Subject: [erlang-questions] spawn_link
> To: erlang-questions@REDACTED
> Message-ID:
> <d8e8f490812290303y3b89841eu645927839fbe2578@REDACTED>
> Content-Type: text/plain; charset="iso-8859-1"
>
> I have a problem of how to get the return value of a function when
>
> spawn_link(Fun) ->pid() is used.
>
> Im going to use above function in following manner.
>
> init([]) ->
>
> ChildPid = erlang:spawn_link(?MODULE, connect_to_server, [Ip,Port, ConId,
> self(),State]).
>
> connect_to_server(Ip, Port, ConId, ParentPid,State) ->
>  case Result= gen_tcp:connect(Ip, Port,
>  [binary, {packet, 0}]) of
>  {ok, Socket} ->
>           io:format("Socket Received:~w~n",[Socket]),
>          ok =(catch gen_server:call(g_srv, {add_conn, self(), ConId,
> Socket})),
>          NewState = State#state{socket= Socket};
>  {error, Reason} ->
>          io:format("connection error host Ip:~w Port: ~w ~w ~n",
> [Ip,Port,Reason]) ,
>         connect_to_server(Ip, Port, ConId, ParentPid,State)
>  end.
>
> I want to get the return value of connect_to_server function. How can I do
> that.
>
> Regards
>
> Thilani




More information about the erlang-questions mailing list