Erlang中通过Port与外部程序交互
2012-12-26 14:33
344 查看
Erlang与外部程序交互大概如下:
erlang:
[/code]
编译执行:
[/code]
erlang:
-module(complex1). -export([start/1, stop/0, init/1]). -export([foo/1, bar/1]). start(ExtPrg) -> spawn(?MODULE, init, [ExtPrg]). stop() -> complex ! stop. foo(X) -> call_port({foo, X}). bar(Y) -> call_port({bar, Y}). call_port(Msg) -> complex ! {call, self(), Msg}, receive {complex, Result} -> Result end. init(ExtPrg) -> register(complex, self()), process_flag(trap_exit, true), Port = open_port({spawn, ExtPrg}, [{packet, 2}]), loop(Port). loop(Port) -> receive {call, Caller, Msg} -> Port ! {self(), {command, encode(Msg)}}, receive {Port, {data, Data}} -> Caller ! {complex, decode(Data)} end, loop(Port); stop -> Port ! {self(), close}, receive {Port, closed} -> exit(normal) end; {'EXIT', Port, Reason} -> exit(port_terminated) end. encode({foo, X}) -> [1, X]; encode({bar, Y}) -> [2, Y]. decode([Int]) -> Int.
[/code]
c程序:
/* erl_comm.c */ typedef unsigned char byte; read_cmd(byte *buf) { int len; if (read_exact(buf, 2) != 2) return(-1); len = (buf[0] << 8) | buf[1]; return read_exact(buf, len); } write_cmd(byte *buf, int len) { byte li; li = (len >> 8) & 0xff; write_exact(&li, 1); li = len & 0xff; write_exact(&li, 1); return write_exact(buf, len); } read_exact(byte *buf, int len) { int i, got=0; do { if ((i = read(0, buf+got, len-got)) <= 0) return(i); got += i; } while (got<len); return(len); }
/* port.c */ typedef unsigned char byte; int main() { int fn, arg, res; byte buf[100]; while (read_cmd(buf) > 0) { fn = buf[0]; arg = buf[1]; if (fn == 1) { res = foo(arg); } else if (fn == 2) { res = bar(arg); } buf[0] = res; write_cmd(buf, 1); } }
编译执行:
unix> gcc -o extprg complex.c erl_comm.c port.c
unix> erl Erlang (BEAM) emulator version 4.9.1.2 Eshell V4.9.1.2 (abort with ^G) 1> c(complex1). {ok,complex1}
2> complex1:start("extprg"). <0.34.0> 3> complex1:foo(3). 4 4> complex1:bar(5). 10 5> complex1:stop(). stop
[/code]
相关文章推荐
- 如何使用Erlang port 和外部程序交互
- QProcess与外部程序的调用(可以通过设置管道来交互)
- 【Erlang新手成长日记】Erlang端口与外部C程序交互
- 通过Windows Service启动外部程序
- 通过URL前缀实现网页和程序交互
- 通过MongoMapper让程序在Rails 3.2上与MongoDB数据交互
- c# 通过Windows服务启动外部程序
- C#中通过Process启动的外部第三方程序MainWindowHandle句柄为0
- 通过jvm api实现从外部对java程序作gc垃圾回收
- AutoCAD2013 + VS2015,不可以直接在“调试”中直接启动外部程序的方式来调试,只能通过在解决方案中加入acad.exe并将acad.exe为启动项
- 如何通过AppDomain用特定的安全上下文加载外部程序集
- 通过sleep让程序等待外部条件改变
- 关于Chrome扩展程序开发 popup.html页面通过jsonp的方式与服务端交互问题
- 在程序中通过Process启动外部exe的方法及注意事项
- C#通过WIN32 API 获取外部程序sysListview的值和TreeView的值
- 通过句柄嵌入程序到外部程序中
- 通过C#程序调用外部程序
- SilverLight浏览器交互之:使用SilverLight程序嵌套外部Html页(附源码)
- c# 通过Windows服务启动外部程序
- Bentley 二次开发 不打开Bentley,外部exe程序中通过COM方式启动的MicroStation