倾听过程Erlang

时间:2017-03-21 08:47:25

标签: erlang file-watcher

我正在尝试根据 synrc/fs library 检测到的文件夹中的更改执行操作。我希望每次 fs &执行动作,例如打印更改的文件名。

我尝试了以下代码,但只是第一次执行!

say_hello() ->
    fs:start_link(fs_watcher, "/Users/foldername"),
    fs:subscribe(fs_watcher),
    receive
        {Watcher_process, {Fs, File_event}, {ChangedFile, Type}} ->
            io:format("~p was ~p ~n",[ChangedFile,File_event])
    end.

任何有用的帮助以及链接&描述如果可能!谢谢:))

2 个答案:

答案 0 :(得分:2)

如果您希望函数继续接收相同类型的消息,可以使用递归:

say_hello() ->
  fs:start_link(fs_watcher, "/Users/foldername"),
  fs:subscribe(fs_watcher),
  recur().

recur()->
  receive
     {Watcher_process, {Fs, File_event}, {ChangedFile, Type}} ->
         io:format("~p was ~p ~n",[ChangedFile,File_event]),
         recur()
  end.

然后你必须考虑一种最终确定功能的方法。

答案 1 :(得分:2)

您需要递归调用receive

say_hello() ->
    fs:start_link(fs_watcher, "/Users/foldername"),
    fs:subscribe(fs_watcher),
    loop().

loop() ->
    receive
        {Watcher_process, {Fs, File_event}, {ChangedFile, Type}} ->
            io:format("~p was ~p ~n",[ChangedFile,File_event]),
            loop()
    end.