File 3511-kernel-Short-circuit-io-message-to-user-in-app-maste.patch of Package erlang
From 2889087545d1c5fb690d09521cd6f22d6a94a98d Mon Sep 17 00:00:00 2001
From: Lukas Larsson <lukas@erlang.org>
Date: Tue, 16 Feb 2021 17:15:44 +0100
Subject: [PATCH 2/2] kernel: Short-circuit io message to user in app master
If the group leader of the application master is init
we know that the message should go to the user process
to we just forward it there directly instead of jumping
via the init process.
---
lib/kernel/src/application_master.erl | 28 +++++++++++++++++++++------
1 file changed, 22 insertions(+), 6 deletions(-)
diff --git a/lib/kernel/src/application_master.erl b/lib/kernel/src/application_master.erl
index 16e453f99f..ccf4d5b831 100644
--- a/lib/kernel/src/application_master.erl
+++ b/lib/kernel/src/application_master.erl
@@ -117,7 +117,11 @@ call(AppMaster, Req) ->
init(Parent, Starter, ApplData, Type) ->
link(Parent),
process_flag(trap_exit, true),
- OldGleader = group_leader(),
+ OldGleader =
+ case group_leader() == whereis(init) of
+ true -> init;
+ false -> group_leader()
+ end,
group_leader(self(), self()),
%% Insert ourselves as master for the process. This ensures that
%% the processes in the application can use get_env/1 at startup.
@@ -158,7 +162,7 @@ start_it(State, Type) ->
init_loop(Pid, Tag, State, Type) ->
receive
IoReq when element(1, IoReq) =:= io_request ->
- State#state.gleader ! IoReq,
+ _ = relay_to_group_leader(IoReq, State),
init_loop(Pid, Tag, State, Type);
{Tag, Res} ->
Res;
@@ -175,7 +179,7 @@ init_loop(Pid, Tag, State, Type) ->
main_loop(Parent, State) ->
receive
IoReq when element(1, IoReq) =:= io_request ->
- State#state.gleader ! IoReq,
+ _ = relay_to_group_leader(IoReq, State),
main_loop(Parent, State);
{'EXIT', Parent, Reason} ->
terminate(Reason, State);
@@ -198,7 +202,7 @@ main_loop(Parent, State) ->
terminate_loop(Child, State) ->
receive
IoReq when element(1, IoReq) =:= io_request ->
- State#state.gleader ! IoReq,
+ _ = relay_to_group_leader(IoReq, State),
terminate_loop(Child, State);
{'EXIT', Child, _} ->
ok;
@@ -231,8 +235,20 @@ terminate(Reason, State = #state{child=Child, children=Children, req=Reqs}) ->
kill_children(Children),
exit(Reason).
-
-
+%% If the group_leader is the `init` process, the message is meant to
+%% end up in `user` so we send it there directly.
+relay_to_group_leader(IoReq, State) ->
+ if
+ State#state.gleader =:= init ->
+ case whereis(user) of
+ undefined ->
+ State#state.gleader ! IoReq;
+ User ->
+ User ! IoReq
+ end;
+ true ->
+ State#state.gleader ! IoReq
+ end.
%%======================================================================
%%======================================================================
--
2.26.2