Piotr Gabryanczyk’s Blog

Java, Refactoring, AOP, Spring, DDD, TDD, etc.

  • Blogroll

    • I have joined Anti-IF Campaign

How to run a system command in Erlang?

Posted by Piotr Gabryanczyk on April 2, 2010

Problem

I would like to be able to run ie. ls -al / from erlang and process the results using erlang. ie.

Files = cmd:run("ls -al /").

Solution

-module(cmd).
-export([run/1, run/2, test/0]).

run(Cmd) -> 
	run(Cmd, 5000).
	
run(Cmd, Timeout) ->
	Port = erlang:open_port({spawn, Cmd},[exit_status]),
	loop(Port,[], Timeout).
	
loop(Port, Data, Timeout) ->
	receive
		{Port, {data, NewData}} -> loop(Port, Data++NewData, Timeout);
		{Port, {exit_status, 0}} -> Data;
		{Port, {exit_status, S}} -> throw({commandfailed, S})
	after Timeout ->
		throw(timeout)
	end.

test() -> 
	shouldReturnCommandResult(),
	shouldThrowAfterTimeout(),
	shouldThrowIfCmdFailed(),
	{ok, "Tests PASSED"}.

shouldReturnCommandResult() ->
	"Hello\n" = run("echo Hello").

shouldThrowAfterTimeout()->
	timeout = (catch run("sleep 10", 20)).
	
shouldThrowIfCmdFailed()->
		{commandfailed, _} = (catch run("wrongcommand")),
		{commandfailed, _} = (catch run("ls nonexistingfile")).

Advertisements

8 Responses to “How to run a system command in Erlang?”

  1. You are reinventing a wheel. There is such function is standard library in module ‘os’:

    Files = os:cmd(“ls -la /”)

  2. Nice:) It was a good erlang kata though 🙂

  3. Eric Manghise said

    The above code fragment is very useful if you just want to get the return code
    from an os command.

  4. DiscreteLogic said

    Data++NewData =:= evil

    Use [NewData|Data] instead. Then

    {Port, {exit_status, 0}} -> lists:reverse(Data);

  5. […] postÄ™py wykonywania polecenia, natrafiÅ‚em na drugi sposób z użyciem portów w Erlangu: How to run a system command in Erlang?. Po dostosowaniu kodu do wÅ‚asnych potrzeb wyglÄ…da on […]

  6. Reblogged this on erlang:get_cookie(). and commented:
    I found this blog post very useful, as I needed a way of calling ejabberdctl script from Common Test case and checking the return code of the command. os:cmd/1 is not good enough, as it returns only standard output, not the code.

  7. kisao said

    Reblogged this on kisao.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: