简体   繁体   中英

How to spawn process with arguments from erlang shell

I do not know what overload of spawn to use when launching a process from the erlang shell , since i need to pass arguments.

A=spawn(
    fun(TID)-> 
           receive {FROM,MSG}->
                  FROM ! {self(),MSG}
           after 0 ->
                  TID !{self(),timeouted}
           end
   end,
   TID
  ).

There is no overload for just the function and arguments. What is the module name when launching from shell ?

I have also tried:

A=spawn(?MODULE,fun()->....,TID).

PS In my case as you can see i need to provide arguments to the spawn method , while running it directly from the erlang shell.

Just embed the definition in a fun:

A = fun(X) ->
    TID = X,             
    spawn(      
        fun()->  
            receive {FROM,MSG}->          
                FROM ! {self(),MSG}    
            after 0 ->                    
                TID !{self(),timeouted}
            end                           
        end                                  
    )
end.

and then you can use A(YourParam) .

Typically, you define a function in a module:

-module(a).
-compile(export_all).

go(X)-> 
    receive {From, Msg}->
        From ! {self(), Msg}
    after 0 ->
        io:format("~s~n", [X])
    end.

Then do this:

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>

Defining functions in the shell is too much of a pain in the ass.

Response to comment:

Here's how you can do simple testing in 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").

In the shell:

1> c(a).

2> a:test().
  2 tests passed.
ok

Here's what happens when a test fails:

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> 

You don't even need to use eunit because you can simply do:

go_test() ->
    "hello" = go("hello").

Then in the shell:

1> c(a).
a.erl:2: Warning: export_all flag enabled - all functions will be exported

2> a:go_test().

You'll get a bad match error if go("hello") doesn't return "hello" :

** exception error: no match of right hand side value "hello" in function a:go_test/0 (a.erl, line 18)

The advantage of using eunit is that with one command, a:test() , you can execute all the functions in the module that end in _test .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM