Erlang中執(zhí)行l(wèi)inux命令的兩種方法
os.cmd(Cmd)
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)單,一般情況下,也滿足了大部分需求。
erlang:open_port(PortName, PortSettings)
當(dāng)os.cmd(Cmd) 滿足不了你的需求的時(shí)候,就可以用強(qiáng)大的open_port(PortName, PortSettings) 來解決了。最簡(jiǎn)單的需求,我要執(zhí)行一個(gè)linux命令,而且還需要返回退出碼。os.cmd(Cmd) 就有些捉急了。也不要以為有了open_port(PortName, PortSettings) 就可以完全替代os.com(Cmd) 了。強(qiáng)大是需要代價(jià)的。
%% 優(yōu)點(diǎn):可以返回exit status 和執(zhí)行過程
%% 缺點(diǎn): 非常影響性能, open_port執(zhí)行的時(shí)候,beam.smp會(huì)阻塞
當(dāng)對(duì)本身系統(tǒng)的性能要求比較高的時(shí)候,不建議使用erlang:open_port(PortName, PortSettings) .
下面是一段很好用的代碼,返回exit status 和執(zhí)行結(jié)果。
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.
相關(guān)文章
Erlang語法學(xué)習(xí)筆記:變量、原子、元組、列表、字符串
這篇文章主要介紹了Erlang語法學(xué)習(xí)筆記:變量、原子、元組、列表、字符串,本文簡(jiǎn)明總結(jié)了這5種類型的相關(guān)知識(shí),需要的朋友可以參考下2015-01-01Erlang中執(zhí)行l(wèi)inux命令的兩種方法
這篇文章主要介紹了Erlang中執(zhí)行l(wèi)inux命令的兩種方法,本文著重講解了erlang:open_port的使用,需要的朋友可以參考下2015-01-01