Erlang中执行linux命令的两种方法

os.cmd(Cmd)

os模块提供了cmd函数可以执行linux系统shell命令(也可以执行windows命令)。返回一个Cmd命令的标准输出字符串结果。例如在linux系统中执行os:cmd("date"). 返回linux的时间。 这种比较简单,一般情况下,也满足了大部分需求。

erlang:open_port(PortName, PortSettings)

当os.cmd(Cmd) 满足不了你的需求的时候,就可以用强大的open_port(PortName, PortSettings) 来解决了。最简单的需求,我要执行一个linux命令,而且还需要返回退出码。os.cmd(Cmd) 就有些捉急了。也不要以为有了open_port(PortName, PortSettings) 就可以完全替代os.com(Cmd) 了。强大是需要代价的。

%% 优点:可以返回exit status 和执行过程
%% 缺点: 非常影响性能, open_port执行的时候,beam.smp会阻塞

当对本身系统的性能要求比较高的时候,不建议使用erlang:open_port(PortName, PortSettings) .

下面是一段很好用的代码,返回exit status 和执行结果。


my_exec(Command) ->

    Port = open_port({spawn, Command}, [stream, in, eof, hide, exit_status]),

    Result = get_data(Port, []),

    Result.

get_data(Port, Sofar) ->     receive     {Port, {data, Bytes}} ->         get_data(Port, [Sofar|Bytes]);     {Port, eof} ->         Port ! {self(), close},         receive         {Port, closed} ->             true         end,         receive         {'EXIT',  Port,  _} ->             ok         after 1 ->              % force context switch             ok         end,         ExitCode =             receive             {Port, {exit_status, Code}} ->                 Code         end,         {ExitCode, lists:flatten(Sofar)}     end.