How to start an OS process in Elixir

What is the best way to run the OS in Elixir?

I expect that I can pass him different parameters at startup, grab his PID and then kill him.

+4
source share
1 answer

To achieve this, you can use the ports:

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"])
+12
source

All Articles