如何在Elixir中启动OS进程 [英] How to start an OS process in Elixir

查看:71
本文介绍了如何在Elixir中启动OS进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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.

推荐答案

您可以使用Ports来实现:

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

这篇关于如何在Elixir中启动OS进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆