【发布时间】:2020-03-26 01:19:38
【问题描述】:
我在运行 100 个传感器时收到来自 Erlang 的响应,所有进程都返回某个版本的
进程 中的错误,退出值: {undef,[{main,watcher_start,[10,0],[]}]}
我不确定自己做错了什么。
这里是main.erl
-module(main).
-import(watcher,[watcher_start/2]).
-import(sensor, [sensor_run/2]).
-compile(export_all).
%given
start() ->
{ok, [ N ]} = io:fread("enter number of sensors> ", "~d"),
if N =< 1 ->
io:fwrite("setup: range must be at least 2~n", []);
true ->
Num_watchers = 1 + (N div 10),
setup_loop(N, Num_watchers)
end.
setup_loop(SenN, Watcher_count) ->
setup_loop(SenN, Watcher_count, 0).
setup_loop(SenN, Watcher_count, SID) when SenN =< 10 ->
spawn(?MODULE, watcher_start, [SenN, SID]);
setup_loop(SenN, Watcher_count, SID) ->
spawn(?MODULE, watcher_start, [10, SID]),
setup_loop(SenN - 10, Watcher_count - 1, SID + 10).
和 watcher.erl
-module(watcher).
-import(sensor, [sensor_run/2]).
-compile(export_all).
watcher_start(SenN, SID) ->
%report start and run the watcher. Generate the list with number of sensors
TheSensorList = gen_list(SenN, SID, []),
io:fwrite("The watcher service is started ~w~n", [TheSensorList]),
watcher_run(TheSensorList).
watcher_run(SensorList) ->
receive
%recieve a measurement, print it out and mainatain the same list as it has not changed
{From, Measurement} ->
io:fwrite("Sensor ~p gave a Measurement of ~p~n", [From, Measurement]),
UpdatedSensorList = SensorList;
%process with PID is down, a sesnor crashed
{'DOWN', _, process, PID, Reason} ->
%Find the sensor ID (SID) of the process that is down
{_, SID} = lists:keyfind(PID, 1, SensorList),
%report the failure that has been deteced
io:fwrite("Sensor ~p has crashed with error ~p i will attempt to restart it~n", [SID, Reason]),
%restart the sensor, the new process will have a new PID & report it
{UpdatedPID, _} = spawn_monitor(sensor, sensor_run, [self(), SID]),
%Now we canm actually updatethe list with a new value
UpdatedSensorList = lists:keyreplace(SID, 2, SensorList, {UpdatedPID, SID}),
io:fwrite("The sensor ~p was restarted with PID ~p", [SID, UpdatedPID])
end,
watcher_run(UpdatedSensorList).
gen_list(SenN, SID, TheList) ->
%create the monitor and continue unil all the SenN number of monitors have been created
{PID, _} = spawn_monitor(sensor, sensor_run, [self(), SID]),
%continue and add the tuple of the new monitor to the list
gen_list(SenN - 1, SID +1, TheList++[{PID, SID}]);
%Base case when we are out of SenN monitors
gen_list(0, _, TheList) ->
TheList.
我做错了什么?我已经导入 watcher_run/2 并且应该向它发送 2 个参数。
【问题讨论】:
-
除了@7Stud 的回答,我建议避免导入:导入不是必需的,只是书面的捷径,也避免 compile(export_all) 并更喜欢明确的导出列表这明确了模块的接口:导出是必要的,并定义了可以从其他模块访问的功能。
标签: erlang