Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start an OS process in Elixir

Tags:

elixir

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.

like image 489
cyberdot Avatar asked Dec 08 '22 06:12

cyberdot


1 Answers

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"])
like image 148
bitwalker Avatar answered Dec 20 '22 22:12

bitwalker