Erlang中執行linux命令的兩種方法_Erlang

來源:互聯網
上載者:User

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.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.