退出价值Undef Erlang Spawn

时间:2016-11-19 00:47:16

标签: concurrency erlang spawn

我在Ubuntu Server计算机上运行以下Erlang代码时遇到错误,它在运行Solus的计算机上正常运行。我是Erlang的新手并且不确定如何读取错误,因为所有其他示例在错误代码中只有一个函数和模块。 我有两个文件 传感器:

-module(sensor).
-export([start/2, senseAndReport/3]).

start(WatcherPid, SensorId) ->
    Ref = make_ref(),
    senseAndReport(WatcherPid, SensorId, Ref).

senseAndReport(WatcherPid, SensorId, Ref) ->
    Measurement = rand:uniform(11),
    if 
        Measurement == 11 ->
            WatcherPid ! {kill, {self(), SensorId}, error},
            exit(error);
        true ->
            WatcherPid ! {Measurement, {self(), SensorId}, Ref}
    end,
    receive
        {ok, Ref} ->
            Sleep_time = rand:uniform(10000),
            timer:sleep(Sleep_time),
            senseAndReport(WatcherPid, SensorId, Ref)
    end.

观察者:

-module(watcher).
-export([start/1, createSensor/3, restartASensor/2, watch/1]).

start(NumOfSensor) ->
    if
        NumOfSensor == 0 ->
            io:format("Please enter a number greater than 0.~n");
        true ->
            createSensor(NumOfSensor, [], 0)
    end.

createSensor(NumOfSensor, SensorList, SensorId) ->
    if
        length(SensorList) == 10 ->
            io:format("Start watching:~n"),
            [io:format("    Id: ~p, Pid: ~p~n", [Id, Pid]) || {Id, Pid} <- SensorList],
            if NumOfSensor /= 0 -> 
                spawn(watcher, createSensor, [NumOfSensor, [], SensorId]),
                watch(SensorList);
            true ->
                watch(SensorList)
            end;
        NumOfSensor == 0 ->
            io:format("Start watching~n"),
            [io:format("    Id: ~p, Pid: ~p~n", [Id, Pid]) || {Id, Pid} <- SensorList],
            watch(SensorList);
        true ->
            SensorPid = spawn_monitor(sensor, start, [self(), SensorId]),
            createSensor(NumOfSensor - 1, lists:merge(SensorList, [{SensorId, SensorPid}]), SensorId + 1)
    end.

restartASensor(SensorList, SensorId) ->
    {SensorPid, _} = spawn_monitor(sensor, start, [self(), SensorId]),
    io:format("    Restarted sensor: ~p, new Pid: ~p~n", [SensorId, SensorPid]),
    NewList = lists:merge(SensorList, [{SensorId, SensorPid}]),
    watch(NewList).

watch(SensorList) ->
    receive
        {kill, {From, FromId}, error} ->
            io:format("    Sensor ~p died~n", [FromId]),
            restartASensor(lists:delete({FromId, From}, SensorList), FromId);
        {Measurement, {From, FromId}, Ref} ->
            io:format("MSG: ~2p, From sensor ~4p~n", [Measurement, FromId]),
            From ! {ok, Ref},
            watch(SensorList)
    end.

这给我以下输出:

Eshell V5.8.5  (abort with ^G)
1> c(watcher).
{ok,watcher}
2> watcher:start(1).
Start watching
    Id: 0, Pid: <0.39.0>

=ERROR REPORT==== 18-Nov-2016::19:32:35 ===
Error in process <0.39.0> with exit value: {undef,[{rand,uniform,[11]},{sensor,senseAndReport,3}]}

1 个答案:

答案 0 :(得分:1)

Dogbert的评论是正确的答案。我使用的Erlang版本在Ubuntu机器上较旧,需要用随机模块替换rand模块。