无法在 erlang 中使用 spawn(Node, Fun) 在远程节点上生成函数

Can not spawn function on remote node with spawn(Node, Fun) in erlang

使用分布式 erlang 进行实验,这是我所拥有的:

 loop()->
    receive {From, ping} ->
            io:format("received ping from ~p~n", [From]),
            From ! pong,
            loop();
        {From, Fun} when is_function(Fun) ->
            io:format("executing function ~p received from ~p~n", [Fun, From]),
            From ! Fun(),
            loop()
    end.

    test_remote_node_can_execute_sent_clojure()->
        Pid = spawn(trecias, fun([])-> loop() end),
        Pid ! {self(), fun()-> erlang:nodes() end},
        receive Result -> 
            Result = [node()]
        after 300 ->
                  timeout
        end.

得到:Can not start erlang:apply,[#Fun<tests.1.123107452>,[]] on trecias

node 我在与节点 'trecias' 相同的机器上运行测试。两个节点都可以加载相同的代码。

知道有什么问题吗?

spawn 调用中,您已将节点名称指定为 trecias,但您需要指定包括主机名在内的完整节点名称,例如trecias@localhost.

此外,您传递给 spawn/2 的函数必须采用零个参数,但上面代码中的函数采用一个参数(如果该参数不是空列表,则会崩溃)。改为 fun() -> loop() end

在远程节点上生成匿名函数时,您还需要确保在两个节点上加载了相同版本的模块。否则你会得到一个 badfun 错误。