emqx_run_sh.erl 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. %%--------------------------------------------------------------------
  2. %% Copyright (c) 2021-2024 EMQ Technologies Co., Ltd. All Rights Reserved.
  3. %%
  4. %% Licensed under the Apache License, Version 2.0 (the "License");
  5. %% you may not use this file except in compliance with the License.
  6. %% You may obtain a copy of the License at
  7. %%
  8. %% http://www.apache.org/licenses/LICENSE-2.0
  9. %%
  10. %% Unless required by applicable law or agreed to in writing, software
  11. %% distributed under the License is distributed on an "AS IS" BASIS,
  12. %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. %% See the License for the specific language governing permissions and
  14. %% limitations under the License.
  15. %%--------------------------------------------------------------------
  16. -module(emqx_run_sh).
  17. -export([do/2]).
  18. do(Command, Options0) ->
  19. Options =
  20. Options0 ++
  21. [
  22. use_stdio,
  23. stderr_to_stdout,
  24. exit_status,
  25. {line, 906},
  26. hide,
  27. eof
  28. ],
  29. Port = erlang:open_port({spawn, Command}, Options),
  30. try
  31. collect_output(Port, [])
  32. after
  33. erlang:port_close(Port)
  34. end.
  35. collect_output(Port, Lines) ->
  36. receive
  37. {Port, {data, {eol, Line}}} ->
  38. collect_output(Port, [Line ++ "\n" | Lines]);
  39. {Port, {data, {noeol, Line}}} ->
  40. collect_output(Port, [Line | Lines]);
  41. {Port, eof} ->
  42. Result = lists:flatten(lists:reverse(Lines)),
  43. receive
  44. {Port, {exit_status, 0}} ->
  45. {ok, Result};
  46. {Port, {exit_status, ExitCode}} ->
  47. {error, {ExitCode, Result}}
  48. end
  49. end.