【问题标题】:How do I send message from the command line to an Erlang process?如何从命令行向 Erlang 进程发送消息?
【发布时间】:2012-10-14 17:45:12
【问题描述】:

我正在尝试通知 Erlang 进程外部程序(Matlab 脚本)已完成。我正在使用批处理文件来执行此操作,并且想输入一个命令来通知 Erlang 进程完成。以下是主要代码:

在 myerlangprogram.erl 中:

runmatlab() ->
      receive
           updatemodel->
               os:cmd("matlabscript.bat"),
...
end.

在 matlabscript.bat 中:

matlab -nosplash -nodesktop -r "addpath('C:/mypath/'); mymatlabscript; %quit;"
%% I would like to notify erlang of completion here....
exit

如您所见,我正在使用 'os:cmd' erlang 函数来调用我的 matlab 脚本。

我不确定这是不是最好的方法。我一直在研究使用端口(http://www.erlang.org/doc/reference_manual/ports.html),但我很难理解端口如何/在何处与操作系统交互。

总之,我的两个问题是: 1. 从命令行向 Erlang 进程发送消息的最简单方法是什么? 2. erlang 端口在哪里/如何从操作系统接收/发送数据?

如有任何建议,我们将不胜感激。

注意操作系统是windows 7。

【问题讨论】:

    标签: matlab command-line operating-system erlang ipc


    【解决方案1】:

    首先,Erlang 进程与 os 进程完全不同。它们之间没有“通知”机制或“消息”机制。你可以做的是 a) 运行新的 erlang 节点,b) 连接到目标节点,c) 向远程节点发送消息。

    但是。关于你的问题。

    runmatlab() ->
          receive
               updatemodel->
                   BatOutput = os:cmd("matlabscript.bat"),
                   %% "here" BAT script has already finished
                   %% and output can be found in BatOutput variable
    ...
    end.
    

    第二个,端口是关于编码/解码 erlang 数据类型(简而言之)。

    【讨论】:

      【解决方案2】:

      我假设您想在不阻塞主进程循环的情况下调用 os:cmd。为了实现这一点,您需要从派生的进程中调用 os:command,然后将消息发送回父进程以指示完成。

      这是一个例子:

      runmatlab() ->
            receive
                 updatemodel ->
                     Parent = self(),
                     spawn_link(fun() ->
                       Response = os:cmd("matlabscript.bat"),
                       Parent ! {updatedmodel, Response}
                     end),
                     runmatlab();
      
                {updatedmodel, Response} ->
                    % do something with response
                    runmatlab()
      end.
      

      【讨论】:

      • 谢谢,我试图实现的基本问题是在 Matlab 脚本运行时暂停整个 Erlang 程序。我现在已经做到了 - 在这里查看我的答案:[stackoverflow.com/questions/13033527/…。另外,关于端口,我不确定是否需要 C 包装器。尽管教科书中的大多数示例似乎都使用了基于 C 的示例。我还是不太明白 erlang 端口是如何与操作系统交互的……
      • 进一步研究你是正确的,端口不需要NIF。这是与regular ruby application 一起使用的端口示例。它似乎正在使用 (STDIN and STDOUT)[github.com/erlyvideo/rack/blob/master/priv/worker.rb#l15-16] 进行通信。
      猜你喜欢
      • 2014-06-07
      • 2010-09-05
      • 2011-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-08
      • 1970-01-01
      相关资源
      最近更新 更多