Skip to content

Instantly share code, notes, and snippets.

@xandkar
Created November 4, 2022 16:08
Show Gist options
  • Save xandkar/20ef60a5ec2faaa069d71ee0e073f88e to your computer and use it in GitHub Desktop.
Save xandkar/20ef60a5ec2faaa069d71ee0e073f88e to your computer and use it in GitHub Desktop.
-spec os_cmd(string()) ->
{integer(), iolist()}.
os_cmd(Command) ->
PortOptions = [stream, exit_status, use_stdio, stderr_to_stdout, in, eof],
PortID = open_port({spawn, Command}, PortOptions),
os_cmd_collect(PortID, []).
-spec os_cmd_collect(port(), iolist()) ->
{integer(), iolist()}.
os_cmd_collect(PortID, Data) ->
receive
{PortID, {data, D}} ->
os_cmd_collect(PortID, [D | Data]);
{PortID, eof} ->
port_close(PortID),
receive
{PortID, {exit_status, ExitCode}} ->
{ExitCode, lists:reverse(Data)}
end
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment