os模塊提供了cmd函數(shù)可以執(zhí)行l(wèi)inux系統(tǒng)shell命令(也可以執(zhí)行windows命令)。返回一個(gè)Cmd命令的標(biāo)準(zhǔn)輸出字符串結(jié)果。例如在linux系統(tǒng)中執(zhí)行os:cmd("date"). 返回linux的時(shí)間。 這種比較簡(jiǎn)單,一般情況下,也滿(mǎn)足了大部分需求。
當(dāng)os.cmd(Cmd) 滿(mǎn)足不了你的需求的時(shí)候,就可以用強(qiáng)大的open_port(PortName, PortSettings) 來(lái)解決了。最簡(jiǎn)單的需求,我要執(zhí)行一個(gè)linux命令,而且還需要返回退出碼。os.cmd(Cmd) 就有些捉急了。也不要以為有了open_port(PortName, PortSettings) 就可以完全替代os.com(Cmd) 了。強(qiáng)大是需要代價(jià)的。
當(dāng)對(duì)本身系統(tǒng)的性能要求比較高的時(shí)候,不建議使用erlang:open_port(PortName, PortSettings) .
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.