[erlang-questions] Executing external commands

Richard Carlsson <>
Mon Feb 12 10:04:20 CET 2007


Fernando Ipar wrote:
> I'm looking for a way to run external commands in erlang and get it's 
> exit code back to erlang.
> As far as I understand, os:cmd(Command) only returns the output of 
> running the program.
> 
> Is there a way to get the exit code from the command, or do I have to 
> implement an external program to run these commands and communicate
> back and forth with erlang through a port?

You can roll your own version of command/1. I use a piece of code
like the following to run external commands in EUnit:

command(Cmd) ->
     Opt = [stream, exit_status, use_stdio,
            stderr_to_stdout, in, eof],
     P = open_port({spawn, Cmd}, Opt),
     get_data(P, []).

get_data(P, D) ->
     receive
         {P, {data, D1}} ->
             get_data(P, [D|D1]);
         {P, eof} ->
             port_close(P),
             receive
                 {P, {exit_status, N}} ->
                     {N, lists:reverse(D)}
             end
     end.



    /Richard




More information about the erlang-questions mailing list