How to execute system command in Erlang and get results using os:cmd/1?

后端 未结 1 1315
暗喜
暗喜 2021-02-09 21:34

When I try to execute following command that returns error or doesn\'t exit on Windows - I always get empty list instead of error returned as string so for example:

I g

相关标签:
1条回答
  • 2021-02-09 22:07

    I am not familiar with windows at all, but I'm sure, you should look this. This is implementation os:cmd/1 function.

    There is problem with os:cmd/1. This function doesn't let you know, was command execution successful or not, so you only have to rely on certain command shell behaviour (which is platform dependent).

    I'd recommend you to use erlang:open_port/2 function. Something like that:

    my_exec(Command) ->
        Port = open_port({spawn, Command}, [stream, in, eof, hide, exit_status]),
        get_data(Port, []).
    
    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.
    

    So function my_exec/1 will return process exit code along with process stdout.

    0 讨论(0)
提交回复
热议问题