Created
June 18, 2015 10:59
-
-
Save upbit/6a74c034ba4eb3804eef to your computer and use it in GitHub Desktop.
erlang cmd.erl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(cmd). | |
%% https://kisao.wordpress.com/2013/12/16/how-to-run-a-system-command-in-erlang/ | |
-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")). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment