【问题标题】:How to start an OS process in Elixir如何在 Elixir 中启动操作系统进程
【发布时间】:2014-08-18 19:38:27
【问题描述】:

在 Elixir 中启动 OS 进程的最佳方式是什么?

我希望能够在启动时向它传递不同的参数, 捕获它的 PID 然后杀死它。

【问题讨论】:

  • 同时检查 System.cmd
  • @OnorioCatenacci System.cmd 在 Windows 上似乎不适合我

标签: elixir


【解决方案1】:

您可以使用 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"])

【讨论】:

  • 你在哪里使用args
  • 哦,哇,不知何故忘记在我的示例模块中添加它。您只需在选项中传递 args: args, 。我将更新代码示例。
  • @bitwalker 在查看了 elixir-lang 谷歌组后,Porcelain 似乎是我的最佳选择
  • 值得注意的是,Porcelain 在幕后使用了端口。如果您打算使用 Ports,这绝对是您要走的路,但了解如何在较低级别工作也很重要:)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-24
  • 2018-09-19
  • 2013-02-26
  • 2018-05-12
  • 2012-10-23
  • 2017-07-14
  • 1970-01-01
相关资源
最近更新 更多