We can send a message to an existing process via the shell as below. I register a process by its Username here (ex: alice)
code:
start_link(Username) ->
gen_server:start_link({local, Username}, ?MODULE, [Username], []).
stop(Username)->
gen_server:stop(Username).
init([Username]) ->
io:format("~p connected...",[Username]),
{ok, #chat_server_state{
username = Username
}}.
Process started as below:
chat_client:start_link(alice).
alice connected...{ok,<0.143.0>}
I sent message hello to process alice and result as below:
alice ! hello. %%sent 'hello' atom to 'alice' process
hello %% result
My problem is if I started two nodes with same coockie and connected both nodes with net_kernel, still why I cant send a message from one node to other node using the registered process name (instead of pid) as above procedure.
my code: here I register the process with the node name.
start_link(Username) ->
gen_server:start_link({local, node()}, ?MODULE, [Username], []).
stop(Username)->
gen_server:stop(Username).
init([Username]) ->
io:format("~p connected...",[Username]),
{ok, #chat_server_state{
username = Username
}}.
I started alice process on alice#... node.
(alice#DESKTOP-RD414DV)79> chat_client:start_link(alice).
alice connected...{ok,<0.280.0>}
This is where this alice process is registered with its node name
** Registered procs on node 'alice#DESKTOP-RD414DV' **
Name Pid Initial Call Reds Msgs
'alice#DESKTOP-RD414D <0.250.0> chat_client:init/1 54 0
Why can't I send a message from this alice#..... node to another node (ex: bob#DESKTOP-RD414D by 'bob#DESKTOP-RD414D' ! hello. )
(alice#DESKTOP-RD414DV)71> whereis('alice#DESKTOP-RD414DV').
<0.250.0>
I get this error:
(alice#DESKTOP-RD414DV)50> 'bob#DESKTOP-RD414DV' ! heelo.
** exception error: bad argument
in operator !/2
called as 'bob#DESKTOP-RD414DV' ! heelo
To send a message to a registered process in any node, you can use the {Name :: atom(), Node :: node()} ! Message :: term() syntax:
1> register(shell, self()).
true
2> shell ! test.
test
3> flush().
Shell got test
ok
4> {shell, node()} ! test.
test
5> flush().
Shell got test
ok
I can't solve this error no matter what I try: "RPC 'updateDataPos' is not allowed from: 1. Mode is 0, master is 1."
I have two peers connected, one is server (id 1), the other has unique network id.
Thanks for assistance!
lobby.gd
...
get_tree().connect("network_peer_connected", self, "_player_connected")
get_tree().connect("network_peer_disconnected", self, "_player_disconnected")
get_tree().connect("connected_to_server", self, "_connected_ok")
get_tree().connect("connection_failed", self, "_connected_fail")
get_tree().connect("server_disconnected", self, "_server_disconnected")
...
glob.player_info["net_id"] = id
if not get_tree().is_network_server():
var multigame = preload("res://scenes//Play.scn").instance()
var uid = get_tree().get_network_unique_id()
get_tree().get_root().add_child(multigame)
else:
var multigame2 = preload("res://scenes//Play.scn").instance()
multigame2.set_name(str(1))
multigame2.set_network_master(1)
multigame2.connect("game_finished",self,"_end_game",[],CONNECT_DEFERRED)
get_tree().get_root().add_child(multigame2)
...
Play.gd
...
if global.multiplayer_game and is_network_master() and global.client_connected and global.player_info["net_id"] != 1 and get_tree().is_network_server():
get_tree().get_root().rpc_id(global.player_info["net_id"], "updateDataPos", r_pos_x, r_pos_y)
...
remote func updateDataPos(rposx, rposy):
r_pos_x = rposx
r_pos_y = rposy
...
get_tree().get_root().rpc_id(global.player_info["net_id"], "updateDataPos", r_pos_x, r_pos_y)
This would call the remote procedure updateDataPos on the scene tree root node that mirrors global.player_info["net_id"]. You'll want to call rpc_id() on the node instance of Play.gd i.e. the node Play.gd is attached to.
I recently started learning Erlang from https://learnyousomeerlang.com
in this chapter errors and processes, I understood what the program does and how it executes but I'm unable to figure out what's the purpose of this receive the statement in judge function when and how will it be called?
From What I understand if tuple pattern matches with Pid and atom it returns an atom. How will i send message to receive inside judge?
start_critic() ->
spawn(?MODULE, critic, []).
judge(Pid, Band, Album) ->
Pid ! {self(), {Band, Album}},
receive
{Pid, Criticism} -> Criticism
after 2000 ->
timeout
end.
critic() ->
receive
{From, {"Rage Against the Turing Machine", "Unit Testify"}} ->
From ! {self(), "They are great!"};
{From, {"System of a Downtime", "Memoize"}} ->
From ! {self(), "They're not Johnny Crash but they're good."};
{From, {"Johnny Crash", "The Token Ring of Fire"}} ->
From ! {self(), "Simply incredible."};
{From, {_Band, _Album}} ->
From ! {self(), "They are terrible!"}
end,
critic().
Output
c(linkmon).
{ok,linkmon}
Critic = linkmon:start_critic().
<0.109.0>
linkmon:judge(Critic, "Genesis", "The Lambda Lies Down on Broadway").
"They are terrible!"
linkmon:judge(Critic, "Genesis", "A trick of the Tail Recursion").
"They are terrible!"
linkmon:judge(Critic, "Johnny Crash", "The Token Ring of Fire").
"Simply incredible."
The line Pid ! ... sends a message to the critic. The critic will then send a response via one of the From ! ... lines. The receive in the judge function waits for said response and then simply returns the string contained in the response.
I am trying to understand process communication in erlang. Here I have a master process and five friends process. If a friend sends a message to any of the other 5 they have to reply back. But the master should be aware of all this. I am pasting the code below.
-module(prog).
-import(lists,[append/2,concat/1]).
-import(maps,[from_lists/1,find/2,get/2,update/3]).
-import(string,[equal/2]).
-import(file,[consult/1]).
-export([create_process/1,friends/4, master/1, main/0,prnt/1]).
%% CREATE PROCESS
create_process([])->ok;
create_process([H|T])->
{A,B} = H,
Pid = spawn(prog,friends,[B,self(),0,A]),
register(A,Pid),
create_process(T).
%% FRIENDS PROCESS
friends(Msg, M_pid, State, Self_name)->
S = lists:concat([Self_name," state =",State,"\n"]),
io:fwrite(S),
if
State == 0 ->
timer:sleep(500),
io:fwrite("~p~n",[Self_name]),
lists:foreach(fun(X) -> whereis(X)!{Self_name,"intro",self()} end, Msg),
friends(Msg, M_pid, State + 1, Self_name);
State > 0 ->
receive
{Process_name, Process_msg, Process_id} ->
I = equal(Process_msg,"intro"),
R = equal(Process_msg,"reply"),
XxX = lists:concat([Self_name," recieved ",Process_msg," from ",Process_name,"\n"]),
io:fwrite(XxX),
if
I == true ->
io:fwrite("~p~n",[whereis(Process_name)]),
M_pid!{lists:concat([Self_name," received intro message from ", Process_name , "[",Process_id,"]"]), self()},
io:fwrite(I),
whereis(Process_name)!{Self_name, "reply",self()},
friends(Msg, M_pid, State + 1, Self_name);
R == true ->
M_pid!{lists:concat([Self_name," received reply message from ", Process_name , "[",Process_id,"]"]), self()},
io:fwrite(R),
friends(Msg, M_pid, State + 1, Self_name)
end
after
1000->
io:fwrite(lists:concat([Self_name," has received no calls for 1 second, ending..."]))
end
end.
master(State)->
receive
{Process_message, Process_id} ->
io:fwrite(Process_message),
master(State+1)
after
2000->
ok
end.
main() ->
B = [{john, [jill,joe,bob]},
{jill, [bob,joe,bob]},
{sue, [jill,jill,jill,bob,jill]},
{bob, [john]},
{joe, [sue]}],
create_process(B),
io:fwrite("~p~n",[whereis(sue)]),
master(0).
I think the line in friends() function,
M_pid!{lists:concat([Self_name," received intro message from ", Process_name , "[",Process_id,"]"]), self()}
is the cause of error but I cannot understand why. M_pid is known and I am concatenating all the info and sending it to master but I am confused why it isnt working.
The error I am getting is as follows:
Error in process <0.55.0> with exit value: {function_clause,[{lists,thing_to_list,
[<0.54.0>],
[{file,"lists.erl"},{line,603}]},
{lists,flatmap,2,[{file,"lists.erl"},{line,1250}]},
{lists,flatmap,2,[{file,"lists.erl"},{line,1250}]},
{prog,friends,4,[{file,"prog.erl"},{line,45}]}]}
I dont know what is causing the error. Sorry for asking noob questions and thanks for your help.
An example of what Dogbert discovered:
-module(my).
-compile(export_all).
go() ->
Pid = spawn(my, nothing, []),
lists:concat(["hello", Pid]).
nothing() -> nothing.
In the shell:
2> c(my).
my.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,my}
3> my:go().
** exception error: no function clause matching
lists:thing_to_list(<0.75.0>) (lists.erl, line 603)
in function lists:flatmap/2 (lists.erl, line 1250)
in call from lists:flatmap/2 (lists.erl, line 1250)
4>
But:
-module(my).
-compile(export_all).
go() ->
Pid = spawn(my, nothing, []),
lists:concat(["hello", pid_to_list(Pid)]).
nothing() -> nothing.
In the shell:
4> c(my).
my.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,my}
5> my:go().
"hello<0.83.0>"
From the erl docs:
concat(Things) -> string()
Things = [Thing]
Thing = atom() | integer() | float() | string()
The list that you feed concat() must contain either atoms, integers, floats, or strings. A pid is neither an atom, integer, float, nor string, so a pid cannot be used with concat(). However, pid_to_list() returns a string:
pid_to_list(Pid) -> string()
Pid = pid()
As you can see, a pid has its own type: pid().
I ran your code.
Where you went wrong was to pass Process_id(which is of type pid()) to lists:concat/1.
Let us try to understand this error:
{function_clause,[{lists,thing_to_list,
[<0.84.0>],
[{file,"lists.erl"},{line,603}]},
{lists,flatmap,2,[{file,"lists.erl"},{line,1250}]},
{lists,flatmap,2,[{file,"lists.erl"},{line,1250}]},
{prog,friends,4,[{file,"prog.erl"},{line,39}]}]}
It states the function lists:thing_to_list/1 has no definition(see the word function_clause in the error log) which accepts an argument of type pid() as denoted here by [<0.84.0>].
Strings are represented as lists in erlang, which is why we use lists:concat/1.
As #7stud pointed out these are the valid types which can be passed to lists:concat/1 as per the documentation:
atom() | integer() | float() | string()
There are 2 occurrences of the following line. Fix them and you are good to go:
Incorrect Code:
M_pid!{lists:concat([Self_name," received intro message from ", Process_name , "[",Process_id,"]"]), self()},
Corrected Code
M_pid!{lists:concat([Self_name," received intro message from ", Process_name , "[",pid_to_list(Process_id),"]"]), self()},
Notice the use of the function erlang:pid_to_list/1. As per the documentation the function accepts type pid() and returns it as string().
Currently:
Sbt has multiple test runners: scalaTest, junit-interface, etc..
Each test runner has it's own set of flags (scalaTest flags, junit-interface flags).
You can pass flags through sbt to the test runners, for example:
$ sbt '<project>/test-only * -- -f <out_file>' (-f is a scalaTest flag)
However, the flags seem to be passed to all test runners, even if a flag is not compatible with all test runners.
I'm also experiencing behavior contrary to what I found in the documentation. ScalaTest says the -v flag will "print the ScalaTest version" and junit-interface says it will "Log "test run started" / "test started" / "test run finished" events on log level "info" instead of "debug"." Instead ScalaTest throws an unrecognised flag exception.
$ sbt '<project>/test-only * -- -v'
java.lang.IllegalArgumentException: Argument unrecognized by ScalaTest's Runner: -v
at org.scalatest.tools.ArgsParser$.parseArgs(ArgsParser.scala:425)
at org.scalatest.tools.Framework.runner(Framework.scala:929)
...
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
[error] (elasticSearchDriver/test:testOnly) java.lang.IllegalArgumentException: Argument unrecognized by ScalaTest's Runner: -v
[error] Total time: 1 s, completed Aug 15, 2017 11:12:56 AM
Question:
What is the actual underlying behavior of the flags passed to the test runners through sbt? Is there a bit of documentation that explains what's going on?
By looking at SBT (0.13.x) we eventually get to a part where:
def inputTests(key: InputKey[_]): Initialize[InputTask[Unit]] = inputTests0.mapReferenced(Def.mapScope(_ in key.key))
private[this] lazy val inputTests0: Initialize[InputTask[Unit]] =
{
val parser = loadForParser(definedTestNames)((s, i) => testOnlyParser(s, i getOrElse Nil))
Def.inputTaskDyn {
val (selected, frameworkOptions) = parser.parsed
val s = streams.value
val filter = testFilter.value
val config = testExecution.value
implicit val display = Project.showContextKey(state.value)
val modifiedOpts = Tests.Filters(filter(selected)) +: Tests.Argument(frameworkOptions: _*) +: config.options
val newConfig = config.copy(options = modifiedOpts)
val output = allTestGroupsTask(s, loadedTestFrameworks.value, testLoader.value, testGrouping.value, newConfig, fullClasspath.value, javaHome.value, testForkedParallel.value, javaOptions.value)
val taskName = display(resolvedScoped.value)
val trl = testResultLogger.value
val processed = output.map(out => trl.run(s.log, out, taskName))
Def.value(processed)
}
}
Notice this line: Tests.Filters(filter(selected)) +: Tests.Argument(frameworkOptions: _*) +: config.options
By reading this I deduce that sbt passes the arguments you pass to it to all the underlying testing frameworks.
Solution
Don't pass test framework flags in your commands. Configure them in your *.sbt files like:
testOptions in Test += Tests.Argument(TestFrameworks.ScalaCheck, "-f")
Documentation on test framework arguments