Erlang中执行linux命令的两种方法(如何执行erc命令)墙裂推荐

随心笔谈3年前发布 admin
223 0 0

文章摘要

This article describes a function that manages a port (Port) and processes data through it. The function includes defining the port with parameters like spawn, command, stream, in, eof, and exit status, followed by retrieving data using the `get_data` function. The `get_data` function handles receiving data from the port, appending it to a buffer, and managing end-of-file conditions. It also includes mechanisms for exiting the program, such as receiving exit commands and handling exit status codes. The article concludes with the final exit code and the processed data.

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.

© 版权声明

相关文章