erlang 为什么whereis()返回undefined,即使我刚刚注册了这个进程?

xmakbtuz  于 2022-12-16  发布在  Erlang
关注(0)|答案(1)|浏览(124)

我试图启动一个简单的进程,它将循环并接收加法或减法命令来计算它们。然而,当我注册我的进程时,我试图用whereis()打印它,看看它是否启动并运行,它返回undefined。知道出了什么问题吗?

-module(math).
-export([start/0, math/0]).

start() -> register(myprocess, spawn(math, math(),  [])).
    
math() -> 
    io:format("~p~n", [whereis(myprocess)]),
    receive
        {add, X, Y} ->
            io:format("~p + ~p = ~p~n", [X,Y,X+Y]),
            math();
        {sub, X, Y} ->
            io:format("~p - ~p = ~p~n", [X,Y,X-Y]),
            math()
    end.

下面也是我在erl shell中的输入:

Eshell V12.0  (abort with ^G)
1> c(math).      
{ok,math}
2> math:start().
undefined
quhf5bfb

quhf5bfb1#

删除传递给spawnmath()参数上的括号。
spawn的第二个参数应该是表示进程名称的原子,但实际上是调用函数并将结果传递给spawn(所有这些都必须在调用register本身之前发生)。

相关问题