What's the best way to start an OS process in Elixir?
I'd expect to be able to pass different parameters to it on start, capture its PID and then kill it.
You can use Ports to achieve this:
defmodule Shell do
def exec(exe, args) when is_list(args) do
port = Port.open({:spawn_executable, exe}, [{:args, args}, :stream, :binary, :exit_status, :hide, :use_stdio, :stderr_to_stdout])
handle_output(port)
end
def handle_output(port) do
receive do
{^port, {:data, data}} ->
IO.puts(data)
handle_output(port)
{^port, {:exit_status, status}} ->
status
end
end
end
iex> Shell.exec("/bin/ls", ["-la", "/tmp"])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With