I asked a similar question yesterday about using one application inside another.
Let's say I want to use an application called x
inside a new module y
.
x
is already compiled and for the sake of simplicity, lets assume it is already running on localhost, and that the objective is to run both components in different nodes.
How can I call functions of x
from within y
?
Would something like rpc:call(Node, x, Fun, Param)
work?
Furthermore, is any (network) setup necessary in order to use the rpc
module?
Important
If you are not able to test connections between two nodes, make sure that you use the command line flag -name
and that you include the whole name in your net_adm:ping/1
call. e.g. if you named your node x@localhost
, you must ping x
from another module by executing net_adm('x@localhost').
. Notice the single-quotes. See this question for more details.
How you call x
depends both on its APIs and on whether or not x
is running in the same node as y
.
If x
is running in the same node as y
and your application dependencies are declared such that x
starts before y
starts, you can simply call into a module of x
the same as calling any other local module.
If x
is in a different node, then yes, using the rpc
module to call into it is one viable option. As long as the y
node can connect to the x
node via Distributed Erlang, rpc
will work without any extra setup.
I mention the API because it's frequently the case that modules do their work by registering their process ids into some sort of name registry, such as the local registry via erlang:register/2
, the global registry, or alternative registries such as gproc, and callers may need to first access the registry directly or indirectly to find the target they're trying to call. For example, when calling a gen_server
instance you typically need to pass as an argument the name or pid of the instance you're trying to call, and for remote calls, the target node name is needed as well.