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

随心笔谈5个月前发布 admin
207 00
🌐 经济型:买域名、轻量云服务器、用途:游戏 网站等 《腾讯云》特点:特价机便宜 适合初学者用 点我优惠购买
🚀 拓展型:买域名、轻量云服务器、用途:游戏 网站等 《阿里云》特点:中档服务器便宜 域名备案事多 点我优惠购买
🛡️ 稳定型:买域名、轻量云服务器、用途:游戏 网站等 《西部数码》 特点:比上两家略贵但是稳定性超好事也少 点我优惠购买

文章摘要

This article describes a program written in an unspecified language that processes data through a port. The program, named `my_exec`, executes a command in parallel and reads data from the specified port, handling it using a recursive function called `get_data`. The `get_data` function reads data from the port in a loop, appending it to a list, until it encounters an end-of-file (`eof`) or receives an exit command. When `eof` is detected, the port is closed, and the program terminates successfully. If the exit command is received, the program stops and returns a success result. The program also handles context switching to improve performance. The core functionality revolves around parallel execution, data processing, and exit handling.

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.

© 版权声明

相关文章