Tuesday, July 3, 2007

Simple command execution

Sometimes you need to run external commands, and just need the return value or exit code...
One simple way to do this is the following:

-export([ execute/2 ]).

execute(Host, Cmd) ->
Port = open_port({spawn, Cmd}, [ {cd, Host}, exit_status, binary ] ),

wait(Port) ->
{Port, {data, BinData}} ->
io:format("dump:~n~p~n", [BinData]),
{Port, {exit_status, Status}} ->
io:format("exit_code: ~p~n", [Status]);
%% {Port, eof} ->
%% port_close(Port);
{Port, exit} ->
io:format("Received : ~p~n", [Port])

Once a port opened your process will receive various messages and one we're interested in is the 'exit_status' one:

{Port, {exit_status, Status}} ->
io:format("exit_code: ~p~n", [Status]);

The variable 'Status' will hold the exit code.

Simple isn't it ?

1 comment:

varsas said...

This is very interesting and looks like just what I needed to know. Keep up the posts! :)