2012-03-02 71 views
0

爲什麼在調用start/0時該程序運行成功,但在致電run/0時不能運行?當我通過撥打run/0啓動程序時,我從gen/tcp得到{error, closed}我應該總是在父進程中調用listen()嗎?

-module(echo_server). 
-compile(export_all). 
run() -> 
    spawn(fun() -> start() end). 
start() -> 
    {ok, Listen} = gen_tcp:listen(12345, [binary,{packet,0}, 
             {reuseaddr,true}, 
             {active, true}]), 
spawn(fun() -> par_connect(Listen) end). 
par_connect(Listen) -> 
    {ok,Socket} = gen_tcp:accept(Listen),  
    spawn(fun() -> par_connect(Listen) end), 
    loop(Socket). 
loop(Socket) -> 
    receive 
     {tcp,Socket,Bin} =Msg -> 
      io:format("received ~p~n",[Msg]), 
      gen_tcp:send(Socket,Bin), 
      loop(Socket); 
     Any -> 
      io:format("any other received ~p~n",[Any]), 
      gen_tcp:close(Socket) 
    end. 

回答

2

當您運行echo_server:start()時,shell將成爲您打開的套接字的所有者。當啓動函數返回時,套接字仍處於打開狀態,因爲shell仍處於活動狀態。如果你故意崩潰你的shell(輸入類似3 = 2的東西),套接字將關閉。

echo_server:另一方面,run()啓動一個擁有套接字的新進程。當啓動返回並且新進程退出時,套接字會關閉。

解決方法之一是讓您的啓動功能停留(例如,添加一個沒有超時的接收)。

+0

謝謝,併爲我遲到抱歉。好答案! – 2012-09-11 08:27:46

相關問題