gen_server for watcher

This commit is contained in:
Fabio Salvini 2017-06-11 16:50:13 +02:00
parent f64408f584
commit f0403bfa26
2 changed files with 27 additions and 11 deletions

View File

@ -54,5 +54,6 @@ isError(Text) ->
end.
startWatcher(File) ->
WatcherPid = spawn_link(watcher, init, [self(), File]),
%% WatcherPid = spawn_link(watcher, init, [self(), File]),
WatcherPid = watcher:start_link(self(), File),
{ok, WatcherPid}.

View File

@ -1,20 +1,35 @@
-module(watcher).
-behaviour(gen_server).
-compile(export_all).
start(MonitorPid, File) ->
spawn_link(?MODULE, init, [MonitorPid, File]).
start_link(MonitorPid, File) ->
gen_server:start_link(?MODULE, [MonitorPid, File], []).
init(MonitorPid, File) ->
init([MonitorPid, File]) ->
io:format("Init~n"),
Cmd = "/usr/bin/tail -n0 --follow=name " ++ File,
Port = open_port({spawn, Cmd}, [stderr_to_stdout, exit_status, binary]),
loop(MonitorPid, Port).
{ok, [MonitorPid, Port]}.
loop(MonitorPid, Port) ->
receive
{Port, {data, {eol, Bin}}} ->
Text = binary_to_list(iolist_to_binary(Bin)),
handle_info(Msg, [MonitorPid, Port]) ->
case Msg of
{Port, {data, Text}} ->
MonitorPid ! {log_line, Text},
loop(MonitorPid, Port);
{noreply, [MonitorPid, Port]};
{Port, {exit_status, _Status}} ->
io:format("Watcher terminated~n")
io:format("Watcher terminated~n"),
{stop, tail_exit, []}
end.
handle_cast(_Msg, State) ->
{noreply, State}.
handle_call(_Request, _From, State) ->
{noreply, State}.
terminate(Reason, _State) ->
io:format("Reason: ~s~n", [Reason]),
shutdown.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.