Starting a new node from inside elixir

How can I start a new node inside the elixir code?

I have tried Node.connect(node_name) but it halts the rest of the program. Is there any way that the node runs in the background?

Can I start it using System.cmd/3 ?

1 Like

You can use the :slave module, e.g.:

$ iex --sname one
# ...
iex(one@my-hostname)1> {:ok, hostname} = :inet.gethostname()
{:ok, 'my-hostname'}
iex(one@my-hostname)2> :slave.start(hostname, :two)
{:ok, :"two@my-hostname"}
iex(one@my-hostname)3> Node.list()                          
[:"two@my-hostname"]

In OTP 25 there will be a new :peer module that I believe will eventually replace :slave

4 Likes

This will start slave node but I want to start a node. When I run it inside my elixir code, I get this error message

** (exit) :not_alive

I have this question, I do not want to start slave, I need to start a new node and maybe the second node is changed something like I put a new function and I need to compile before, but the main or one node should be the old source-compiled.

I can do this:

iex --name a@127.0.0.1 -S mix
iex(a@127.0.0.1)11> pid = spawn(fn -> System.cmd("iex", ["--name", "c@127.0.0.1", "-S", "mix"]) end)
#PID<0.172.0>
iex(a@127.0.0.1)12> Node.list
[:"b@127.0.0.1"]
iex(a@127.0.0.1)13> Node.connect :"c@127.0.0.1"
true
iex(a@127.0.0.1)2> Node.list
[:"b@127.0.0.1", :"c@127.0.0.1"]
iex(a@127.0.0.1)14> Node.spawn_link(:"c@127.0.0.1", fn -> IO.inspect Hellow.test4() end) |> IO.inspect
#PID<18956.174.0>
#PID<18956.174.0>
"this is test 4"

But how can I know the new node of code is compiled or not? And if is there a compile error, how can be able to get the error?

I solved my problem with System.cmd("mix", ["deps.compile"], into: IO.stream()), if you have another suggestion, please let me know