Programming Erlang 13.9 练习:编写一个 my_spawn 函数

版权声明:@潘广宇博客, https://blog.csdn.net/panguangyuu/article/details/89163123

一、题目

编写一个my_spawn(Mod, Func, Args)函数。它的行为类似spawn(Mod, Func, Args),但有一点区别。如果分裂出的进程挂了,就应打印一个消息,说明进程挂掉的原因以及在此之前存活了多长时间

二、编写 

myspawn 模块

-module(myspawn).
-export([my_spawn/3]).

my_spawn(Mod, Func, Args) ->
    statistics(runtime),                            % 记录初始调用时间
    Pid = spawn(Mod, Func, Args),                   % 调用 spawn 分裂进程
    Ref = monitor(process, Pid),                    % 监听分裂的进程状态
    receive
        {'DOWN', Ref, process, Pid, Why} ->     % 当分裂进程意外退出时,模式匹配
        {_, Time2} = statistics(runtime),
        Time3 = Time2 * 1000, 
        io:format("Down Reason : ~p ; Time : ~p MicroSeconds", [Why, Time3])       
    end.

testmyspawn 模块,(用于spawn创建的函数)

-module(testmyspawn).
-export([test/1]).

test(X) -> 
    receive
    after 22222 ->
        list_to_atom(X)          % 函数执行到22222毫秒后返回
    end.

测试原理,通过传入非法的X给testmyspawn模块使其报错,并将错误发送给父进程

c(myspawn).

c(testmyspawn).

myspawn:my_spawn(testmyspawn, test, [1]).    % 第三个参数传入了一个非list,让分裂进程在22222毫秒后报错

%%% 过了 22222 毫秒后...

% 返回信息:

Down Reason : {badarg,[{erlang,list_to_atom,[1],[]},
                       {testmyspawn,test,1,
                                    [{file,"testmyspawn.erl"},{line,7}]}]} ; Time : 1000 MicroSecondsok

...

猜你喜欢

转载自blog.csdn.net/panguangyuu/article/details/89163123