Is it possible to timeout a System.cmd(...)?

487 views
Skip to first unread message

Vince Marco

unread,
Apr 10, 2014, 10:37:55 AM4/10/14
to elixir-l...@googlegroups.com
I am building a DevOps tool that needs to execute OS commands.  Is it possible to timeout a System.cmd(...)?

Actually this is a redesign from a Java/Groovy tool, and one of the main draws is to move command execution to actors.  Is there a way to manage the timeout in the actor?  My main concern is a "hung" command that doesn't return.  It seems the actor would also be prevented from receiving msgs while stuck on the hung System.cmd(...).

Thanks in advance,

Vince

Alexei Sholik

unread,
Apr 10, 2014, 11:26:58 AM4/10/14
to elixir-l...@googlegroups.com
Use ports instead. When you open a port, you get a pid. Your process will then receive output from the command as messages from that pid. So you could do something like the following:

port = Port.open(...)
{:os_pid, ospid} = Port.info(port, :os_pid)

# note that if the program terminated before the call to Port.info, you'll get :undefined back

receive do
  {^port, {:data, data}} -> ...
  after <timeout> ->
    System.cmd "kill #{ospid}"
end

If your program constantly produces output, you could fire a timer

{:ok, _} = :timer.send_after(1000, {:kill_this_process, ospid})

receive do
  {^port, {:data, data}} -> ...
  {:kill_this_process, ospid} ->
    System.cmd "kill #{ospid}"
end

---

To create a port that is somewhat equivalent to System.cmd, use this:

sh = :os.find_executable('sh')
command = "something something"
port = Port.open({:spawn_executable, sh}, [:stream, :binary, {:args, ["-c", command]}, :use_stdio, :stderr_to_stdout, :exit_status])



--
You received this message because you are subscribed to the Google Groups "elixir-lang-talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elixir-lang-ta...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
Best regards
Alexei Sholik
Reply all
Reply to author
Forward
0 new messages