9

当我尝试执行以下返回错误或在 Windows 上不退出的命令时 - 我总是得到空列表,而不是作为字符串返回的错误,例如:

我得到:

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

而不是像

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

在 linux 中 - 一切都按预期工作,所以我得到 "/bin/sh: line 1: blah: command not found\n"

因此,当我需要知道执行如何完成等时,我不能依赖该函数。请提出一些通用的方法来执行命令并获得包括错误代码在内的结果。

谢谢!

4

1 回答 1

11

我对 Windows 一点也不熟悉,但我敢肯定,你应该看看 这个。这是实现os:cmd/1功能。

有问题os:cmd/1。此功能不会让您知道命令执行是否成功,因此您只需要依赖某些命令外壳行为(取决于平台)。

我建议你使用erlang:open_port/2函数。像这样的东西:

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.

因此函数my_exec/1将返回进程退出代码以及进程标准输出。

于 2014-11-20T19:06:24.797 回答