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.
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"])