how to execute system command in erlang and get results - unreliable os:cmd/1

血红的双手。 提交于 2019-12-05 03:14:36

问题


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 get:

[] = os:cmd("blah").

instead of something like

"command not found" = os:cmd("blah").

In linux - everything works as expected so I get "/bin/sh: line 1: blah: command not found\n"

Therefore I cannot rely on that function when I need to know how execution finished etc. Please suggest some general way how to execute command and get results including error code.

Thanks!


回答1:


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.



来源:https://stackoverflow.com/questions/27028486/how-to-execute-system-command-in-erlang-and-get-results-unreliable-oscmd-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!