[英]How to spawn process with arguments from erlang shell
我不知道该怎么过载的spawn
从Erlang shell的启动过程时,因为我需要通过参数来使用。
A=spawn(
fun(TID)->
receive {FROM,MSG}->
FROM ! {self(),MSG}
after 0 ->
TID !{self(),timeouted}
end
end,
TID
).
仅function
和参数没有重载。 从shell启动时,模块名称是什么?
我也尝试过:
A=spawn(?MODULE,fun()->....,TID).
PS在我看来,如您所见,我需要在直接从erlang shell运行它的同时为spawn
方法提供参数。
只是在一个有趣的嵌入定义:
A = fun(X) ->
TID = X,
spawn(
fun()->
receive {FROM,MSG}->
FROM ! {self(),MSG}
after 0 ->
TID !{self(),timeouted}
end
end
)
end.
然后可以使用A(YourParam)
。
通常,您在模块中定义一个函数:
-module(a).
-compile(export_all).
go(X)->
receive {From, Msg}->
From ! {self(), Msg}
after 0 ->
io:format("~s~n", [X])
end.
然后执行以下操作:
9> c(a).
a.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,a}
10> Pid = spawn(a, go, ["hello"]).
hello
<0.95.0>
在外壳中定义功能实在太麻烦了。
对评论的回应:
这是您可以在erlang中进行简单测试的方法:
-module(a).
-compile(export_all).
-include_lib("eunit/include/eunit.hrl").
do(Y) ->
Y.
go(X)->
receive {From, Msg}->
From ! {self(), Msg}
after 0 ->
X
end.
do_test() ->
10 = do(10).
go_test() ->
"hello" = go("hello").
在外壳中:
1> c(a).
2> a:test().
2 tests passed.
ok
测试失败时会发生以下情况:
5> a:test().
a: go_test...*failed*
in function a:go_test/0 (a.erl, line 18)
**error:{badmatch,"hello"}
output:<<"">>
=======================================================
Failed: 1. Skipped: 0. Passed: 1.
error
6>
您甚至不需要使用eunit,因为您只需执行以下操作:
go_test() ->
"hello" = go("hello").
然后在外壳中:
1> c(a).
a.erl:2: Warning: export_all flag enabled - all functions will be exported
2> a:go_test().
如果go("hello")
不返回"hello"
则会go("hello")
匹配错误:
**异常错误:函数a:go_test / 0(a.erl,第18行)中右侧值“ hello”不匹配
使用eunit的优点是,只需一个命令a:test()
,您就可以执行模块中以_test
结尾的所有功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.