5

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.

cyberdot
  • 177
  • 1
  • 9

1 Answers1

15

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"])
bitwalker
  • 9,061
  • 1
  • 35
  • 27
  • where do you use the `args`? – Uri Agassi Aug 17 '14 at 07:35
  • Oh wow, somehow forgot to add that in my example module. You just pass args: args, in the options. I'll update the code sample. – bitwalker Aug 18 '14 at 11:37
  • 1
    @bitwalker after checking on elixir-lang google group, **[Porcelain](http://porcelain.readthedocs.org/en/v1.1.1/)** seems like the best option for me to go with – cyberdot Aug 18 '14 at 14:17
  • 5
    It's worth noting that Porcelain uses Ports under the covers. It's definitely the way to go if you plan on using Ports, but it's important to know how to work at the lower level too :). – bitwalker Aug 18 '14 at 20:35