-
Notifications
You must be signed in to change notification settings - Fork 3k
/
proc_lib.erl
1602 lines (1391 loc) · 55.4 KB
/
proc_lib.erl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
%%
%% %CopyrightBegin%
%%
%% Copyright Ericsson AB 1996-2024. All Rights Reserved.
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%%
-module(proc_lib).
-moduledoc """
Functions for asynchronous and synchronous start of processes adhering to the
OTP design principles.
This module is used to start processes adhering to the
[OTP Design Principles](`e:system:design_principles.md`). Specifically, the
functions in this module are used by the OTP standard behaviors (for example,
`m:gen_server` and `m:gen_statem`) when starting new processes. The functions can
also be used to start _special processes_, user-defined processes that comply to
the OTP design principles. For an example, see section
[sys and proc_lib](`e:system:spec_proc.md`) in OTP Design Principles.
Some useful information is initialized when a process starts. The registered
names, or the process identifiers, of the parent process, and the parent
ancestors, are stored together with information about the function initially
called in the process.
While in "plain Erlang", a process is said to terminate normally only for exit
reason `normal`, a process started using `m:proc_lib` is also said to terminate
normally if it exits with reason `shutdown` or `{shutdown,Term}`. `shutdown` is
the reason used when an application (supervision tree) is stopped.
When a process that is started using `m:proc_lib` terminates abnormally (that is,
with another exit reason than `normal`, `shutdown`, or `{shutdown,Term}`), a
_crash report_ is generated, which is written to terminal by the default logger
handler setup by Kernel. For more information about how crash reports were
logged prior to Erlang/OTP 21.0, see
[SASL Error Logging](`e:sasl:error_logging.md`) in the SASL User's Guide.
Unlike in "plain Erlang", `m:proc_lib` processes will not generate _error
reports_, which are written to the terminal by the emulator. All exceptions are
converted to _exits_ which are ignored by the default `logger` handler.
The crash report contains the previously stored information, such as ancestors
and initial function, the termination reason, and information about other
processes that terminate as a result of this process terminating.
## See Also
`m:logger`
""".
%% This module is used to set some initial information
%% in each created process.
%% Then a process terminates the Reason is checked and
%% a crash report is generated if the Reason was not expected.
-export([spawn/1, spawn_link/1, spawn/2, spawn_link/2,
spawn/3, spawn_link/3, spawn/4, spawn_link/4,
spawn_opt/2, spawn_opt/3, spawn_opt/4, spawn_opt/5,
start/3, start/4, start/5, start_link/3, start_link/4, start_link/5,
start_monitor/3, start_monitor/4, start_monitor/5,
hibernate/3,
init_ack/1, init_ack/2,
init_fail/2, init_fail/3,
init_p/3,init_p/5,format/1,format/2,format/3,report_cb/2,
initial_call/1,
translate_initial_call/1,
set_label/1, get_label/1,
stop/1, stop/3]).
%% Internal exports.
-export([wake_up/3]).
-export_type([spawn_option/0]).
-export_type([start_spawn_option/0]).
-include("logger.hrl").
%%-----------------------------------------------------------------------------
%% This shall be spawn_option() -- monitor options and must be kept in sync
%% (with erlang:spawn_opt_options())
%%
-doc """
A restricted set of [spawn options](`t:spawn_option/0`). Most notably `monitor`
is _not_ part of these options.
""".
-type start_spawn_option() :: 'link'
| {'priority', erlang:priority_level()}
| {'fullsweep_after', non_neg_integer()}
| {'min_heap_size', non_neg_integer()}
| {'min_bin_vheap_size', non_neg_integer()}
| {'max_heap_size', erlang:max_heap_size()}
| {'message_queue_data', erlang:message_queue_data() }.
%% and this macro is used to verify that there are no monitor options
%% which also needs to be kept in sync all kinds of monitor options
%% in erlang:spawn_opt_options().
%%
-define(VERIFY_NO_MONITOR_OPT(M, F, A, T, Opts),
Monitor = monitor,
case lists:member(Monitor, Opts) of
true ->
erlang:error(badarg, [M,F,A,T,Opts]);
false ->
case lists:keyfind(Monitor, 1, Opts) of
false ->
ok;
{Monitor, _} ->
erlang:error(badarg, [M,F,A,T,Opts])
end
end).
-doc """
An exception passed to `init_fail/3`. See `erlang:raise/3` for a description
of `Class`, `Reason` and `Stacktrace`.
""".
-type exception() :: {Class :: 'error' | 'exit' | 'throw', Reason :: term()} |
{Class :: 'error' | 'exit' | 'throw', Reason :: term(),
Stacktrace :: erlang:raise_stacktrace()}.
-doc "Equivalent to `t:erlang:spawn_opt_option/0`.".
-type spawn_option() :: erlang:spawn_opt_option().
-type dict_or_pid() :: pid()
| (ProcInfo :: [_])
| {X :: integer(), Y :: integer(), Z :: integer()}.
%%-----------------------------------------------------------------------------
%%-----------------------------------------------------------------------------
-doc(#{equiv => spawn(erlang, apply, [Fun])}).
-spec spawn(Fun) -> pid() when
Fun :: function().
spawn(F) when is_function(F) ->
Parent = get_my_name(),
Ancestors = get_ancestors(),
erlang:spawn(?MODULE, init_p, [Parent,Ancestors,F]).
-doc(#{equiv => spawn(node(), Module, Function, Args)}).
-spec spawn(Module, Function, Args) -> pid() when
Module :: module(),
Function :: atom(),
Args :: [term()].
spawn(M,F,A) when is_atom(M), is_atom(F), is_list(A) ->
Parent = get_my_name(),
Ancestors = get_ancestors(),
erlang:spawn(?MODULE, init_p, [Parent,Ancestors,M,F,A]).
-doc(#{equiv => spawn_link(erlang, apply, [Fun])}).
-spec spawn_link(Fun) -> pid() when
Fun :: function().
spawn_link(F) when is_function(F) ->
Parent = get_my_name(),
Ancestors = get_ancestors(),
erlang:spawn_link(?MODULE, init_p, [Parent,Ancestors,F]).
-doc(#{equiv => spawn_link(node(), Module, Function, Args)}).
-spec spawn_link(Module, Function, Args) -> pid() when
Module :: module(),
Function :: atom(),
Args :: [term()].
spawn_link(M,F,A) when is_atom(M), is_atom(F), is_list(A) ->
Parent = get_my_name(),
Ancestors = get_ancestors(),
erlang:spawn_link(?MODULE, init_p, [Parent,Ancestors,M,F,A]).
-doc(#{equiv => spawn(Node, apply, erlang, [Fun])}).
-spec spawn(Node, Fun) -> pid() when
Node :: node(),
Fun :: function().
spawn(Node, F) when is_function(F) ->
Parent = get_my_name(),
Ancestors = get_ancestors(),
erlang:spawn(Node, ?MODULE, init_p, [Parent,Ancestors,F]).
-doc """
Spawns a new process and initializes it as described in the beginning of this
manual page. The process is spawned using the [`spawn`](`erlang:spawn/1`) BIFs.
""".
-spec spawn(Node, Module, Function, Args) -> pid() when
Node :: node(),
Module :: module(),
Function :: atom(),
Args :: [term()].
spawn(Node, M, F, A) when is_atom(M), is_atom(F), is_list(A) ->
Parent = get_my_name(),
Ancestors = get_ancestors(),
erlang:spawn(Node, ?MODULE, init_p, [Parent,Ancestors,M,F,A]).
-doc(#{equiv => spawn_link(Node, erlang, apply, [Fun])}).
-spec spawn_link(Node, Fun) -> pid() when
Node :: node(),
Fun :: function().
spawn_link(Node, F) when is_function(F) ->
Parent = get_my_name(),
Ancestors = get_ancestors(),
erlang:spawn_link(Node, ?MODULE, init_p, [Parent,Ancestors,F]).
-doc """
Spawns a new process and initializes it as described in the beginning of this
manual page. The process is spawned using the
[`spawn_link`](`erlang:spawn_link/1`) BIFs.
""".
-spec spawn_link(Node, Module, Function, Args) -> pid() when
Node :: node(),
Module :: module(),
Function :: atom(),
Args :: [term()].
spawn_link(Node, M, F, A) when is_atom(M), is_atom(F), is_list(A) ->
Parent = get_my_name(),
Ancestors = get_ancestors(),
erlang:spawn_link(Node, ?MODULE, init_p, [Parent,Ancestors,M,F,A]).
-doc(#{equiv => spawn_opt(erlang, apply, [Fun], SpawnOpts)}).
-spec spawn_opt(Fun, SpawnOpts) -> pid() | {pid(), reference()} when
Fun :: function(),
SpawnOpts :: [erlang:spawn_opt_option()].
spawn_opt(F, Opts) when is_function(F) ->
Parent = get_my_name(),
Ancestors = get_ancestors(),
erlang:spawn_opt(?MODULE, init_p, [Parent,Ancestors,F],Opts).
-doc(#{equiv => spawn_opt(Node, erlang, apply, [Fun], SpawnOpts)}).
-spec spawn_opt(Node, Fun, SpawnOpts) -> pid() | {pid(), reference()} when
Node :: node(),
Fun :: function(),
SpawnOpts :: [erlang:spawn_opt_option()].
spawn_opt(Node, F, Opts) when is_function(F) ->
Parent = get_my_name(),
Ancestors = get_ancestors(),
erlang:spawn_opt(Node, ?MODULE, init_p, [Parent,Ancestors,F], Opts).
-doc(#{equiv => spawn_opt(node(), Module, Function, Args, SpawnOpts)}).
-spec spawn_opt(Module, Function, Args, SpawnOpts) -> pid() | {pid(), reference()} when
Module :: module(),
Function :: atom(),
Args :: [term()],
SpawnOpts :: [erlang:spawn_opt_option()].
spawn_opt(M, F, A, Opts) when is_atom(M), is_atom(F), is_list(A) ->
Parent = get_my_name(),
Ancestors = get_ancestors(),
erlang:spawn_opt(?MODULE, init_p, [Parent,Ancestors,M,F,A], Opts).
-doc """
Spawns a new process and initializes it as described in the beginning of this
manual page. The process is spawned using the
[`erlang:spawn_opt`](`erlang:spawn_opt/2`) BIFs.
""".
-spec spawn_opt(Node, Module, Function, Args, SpawnOpts) -> pid() | {pid(), reference()} when
Node :: node(),
Module :: module(),
Function :: atom(),
Args :: [term()],
SpawnOpts :: [erlang:spawn_opt_option()].
spawn_opt(Node, M, F, A, Opts) when is_atom(M), is_atom(F), is_list(A) ->
Parent = get_my_name(),
Ancestors = get_ancestors(),
erlang:spawn_opt(Node, ?MODULE, init_p, [Parent,Ancestors,M,F,A], Opts).
spawn_mon(M,F,A) ->
Parent = get_my_name(),
Ancestors = get_ancestors(),
erlang:spawn_monitor(?MODULE, init_p, [Parent,Ancestors,M,F,A]).
-doc """
This function does the same as (and does call) the
[`hibernate/3`](`erlang:hibernate/3`) BIF, but ensures that exception handling
and logging continues to work as expected when the process wakes up.
Always use this function instead of the BIF for processes started using
`proc_lib` functions.
""".
-spec hibernate(Module, Function, Args) -> no_return() when
Module :: module(),
Function :: atom(),
Args :: [term()].
hibernate(M, F, A) when is_atom(M), is_atom(F), is_list(A) ->
erlang:hibernate(?MODULE, wake_up, [M, F, A]).
-doc false.
-spec init_p(pid(), [pid()], function()) -> term().
init_p(Parent, Ancestors, Fun) when is_function(Fun) ->
put('$ancestors', [Parent|Ancestors]),
Mfa = erlang:fun_info_mfa(Fun),
put('$initial_call', Mfa),
try
Fun()
catch
Class:Reason:Stacktrace ->
exit_p(Class, Reason, Stacktrace)
end.
-doc false.
-spec init_p(pid(), [pid()], atom(), atom(), [term()]) -> term().
init_p(Parent, Ancestors, M, F, A) when is_atom(M), is_atom(F), is_list(A) ->
put('$ancestors', [Parent|Ancestors]),
put('$initial_call', trans_init(M, F, A)),
init_p_do_apply(M, F, A).
init_p_do_apply(M, F, A) ->
try
apply(M, F, A)
catch
Class:Reason:Stacktrace ->
exit_p(Class, Reason, Stacktrace)
end.
-doc false.
-spec wake_up(atom(), atom(), [term()]) -> term().
wake_up(M, F, A) when is_atom(M), is_atom(F), is_list(A) ->
try
apply(M, F, A)
catch
Class:Reason:Stacktrace ->
exit_p(Class, Reason, Stacktrace)
end.
exit_p(Class, Reason, Stacktrace) ->
case get('$initial_call') of
{M,F,A} when is_atom(M), is_atom(F), is_integer(A) ->
MFA = {M,F,make_dummy_args(A, [])},
crash_report(Class, Reason, MFA, Stacktrace),
erlang:raise(exit, exit_reason(Class, Reason, Stacktrace), Stacktrace);
_ ->
%% The process dictionary has been cleared or
%% possibly modified.
crash_report(Class, Reason, [], Stacktrace),
erlang:raise(exit, exit_reason(Class, Reason, Stacktrace), Stacktrace)
end.
exit_reason(error, Reason, Stacktrace) ->
{Reason, Stacktrace};
exit_reason(exit, Reason, _Stacktrace) ->
Reason;
exit_reason(throw, Reason, Stacktrace) ->
{{nocatch, Reason}, Stacktrace}.
-doc(#{equiv => start(Module, Function, Args, infinity)}).
-spec start(Module, Function, Args) -> Ret when
Module :: module(),
Function :: atom(),
Args :: [term()],
Ret :: term() | {error, Reason :: term()}.
start(M, F, A) when is_atom(M), is_atom(F), is_list(A) ->
start(M, F, A, infinity).
-doc(#{equiv => start(Module, Function, Args, Time, [])}).
-spec start(Module, Function, Args, Time) -> Ret when
Module :: module(),
Function :: atom(),
Args :: [term()],
Time :: timeout(),
Ret :: term() | {error, Reason :: term()}.
start(M, F, A, Timeout) when is_atom(M), is_atom(F), is_list(A) ->
sync_start(spawn_mon(M, F, A), Timeout).
-doc """
Starts a new process synchronously. Spawns the process and waits for it to
start.
To indicate a succesful start, the started process _must_ call
[`init_ack(Parent, Ret)`](`init_ack/2`) where `Parent` is the process that
evaluates this function, or [`init_ack(Ret)`](`init_ack/1`). `Ret` is then
returned by this function.
If the process fails to start, it _must_ fail; preferably by calling
[`init_fail(Parent, Ret, Exception)` ](`init_fail/3`) where `Parent` is the
process that evaluates this function, or
[`init_fail(Ret, Exception)`](`init_fail/2`). `Ret` is then returned by this
function, and the started process fails with `Exception`.
If the process instead fails before calling `init_ack/1,2` or `init_fail/2,3`,
this function returns `{error, Reason}` where `Reason` depends a bit on the
exception just like for a process link `{'EXIT',Pid,Reason}` message.
If `Time` is specified as an integer, this function waits for `Time`
milliseconds for the new process to call `init_ack/1,2` or `init_fail/2,3`,
otherwise the process gets killed and `Ret = {error, timeout}` is returned.
Argument `SpawnOpts`, if specified, is passed as the last argument to the
[`spawn_opt/4`](`erlang:spawn_opt/4`) BIF.
> #### Note {: .info }
>
> Using spawn option `monitor` is not allowed. It causes the function to fail
> with reason `badarg`.
>
> Using spawn option `link` will set a link to the spawned process, just like
> [start_link/3,4,5](`start_link/3`).
""".
-spec start(Module, Function, Args, Time, SpawnOpts) -> Ret when
Module :: module(),
Function :: atom(),
Args :: [term()],
Time :: timeout(),
SpawnOpts :: [start_spawn_option()],
Ret :: term() | {error, Reason :: term()}.
start(M, F, A, Timeout, SpawnOpts) when is_atom(M), is_atom(F), is_list(A) ->
?VERIFY_NO_MONITOR_OPT(M, F, A, Timeout, SpawnOpts),
sync_start(?MODULE:spawn_opt(M, F, A, [monitor|SpawnOpts]), Timeout).
sync_start({Pid, Ref}, Timeout) ->
receive
{ack, Pid, Return} ->
erlang:demonitor(Ref, [flush]),
Return;
{nack, Pid, Return} ->
flush_EXIT(Pid),
_ = await_DOWN(Pid, Ref),
Return;
{'DOWN', Ref, process, Pid, Reason} ->
flush_EXIT(Pid),
{error, Reason}
after Timeout ->
kill_flush_EXIT(Pid),
_ = await_DOWN(Pid, Ref),
{error, timeout}
end.
-doc(#{equiv => start_link(Module, Function, Args, infinity)}).
-spec start_link(Module, Function, Args) -> Ret when
Module :: module(),
Function :: atom(),
Args :: [term()],
Ret :: term() | {error, Reason :: term()}.
start_link(M, F, A) when is_atom(M), is_atom(F), is_list(A) ->
start_link(M, F, A, infinity).
-doc(#{equiv => start_link(Module, Function, Args, Time, [])}).
-spec start_link(Module, Function, Args, Time) -> Ret when
Module :: module(),
Function :: atom(),
Args :: [term()],
Time :: timeout(),
Ret :: term() | {error, Reason :: term()}.
start_link(M, F, A, Timeout) when is_atom(M), is_atom(F), is_list(A) ->
sync_start(?MODULE:spawn_opt(M, F, A, [link,monitor]), Timeout).
-doc """
Starts a new process synchronously. Spawns the process and waits for it to
start. A link is atomically set on the newly spawned process.
> #### Note {: .info }
>
> If the started process gets killed or crashes with a reason that is not
> `normal`, the process link will kill the calling process so this function does
> not return, unless the calling process traps exits. For example, if this
> function times out it will kill the spawned process, and then the link might
> kill the calling process.
Besides setting a link on the spawned process this function behaves like
[start/5](`start/5`).
When the calling process traps exits; if this function returns due to the
spawned process exiting (any error return), this function receives (consumes)
the `'EXIT'` message, also when this function times out and kills the spawned
process.
> #### Note {: .info }
>
> Using spawn option `monitor` is not allowed. It causes the function to fail
> with reason `badarg`.
""".
-spec start_link(Module, Function, Args, Time, SpawnOpts) -> Ret when
Module :: module(),
Function :: atom(),
Args :: [term()],
Time :: timeout(),
SpawnOpts :: [start_spawn_option()],
Ret :: term() | {error, Reason :: term()}.
start_link(M,F,A,Timeout,SpawnOpts) when is_atom(M), is_atom(F), is_list(A) ->
?VERIFY_NO_MONITOR_OPT(M, F, A, Timeout, SpawnOpts),
sync_start(
?MODULE:spawn_opt(M, F, A, [link,monitor|SpawnOpts]), Timeout).
-doc(#{equiv => start_monitor(Module, Function, Args, infinity)}).
-doc(#{since => <<"OTP 23.0">>}).
-spec start_monitor(Module, Function, Args) -> {Ret, Mon} when
Module :: module(),
Function :: atom(),
Args :: [term()],
Mon :: reference(),
Ret :: term() | {error, Reason :: term()}.
start_monitor(M, F, A) when is_atom(M), is_atom(F), is_list(A) ->
start_monitor(M, F, A, infinity).
-doc(#{equiv => start_monitor(Module, Function, Args, Time, [])}).
-doc(#{since => <<"OTP 23.0">>}).
-spec start_monitor(Module, Function, Args, Time) -> {Ret, Mon} when
Module :: module(),
Function :: atom(),
Args :: [term()],
Time :: timeout(),
Mon :: reference(),
Ret :: term() | {error, Reason :: term()}.
start_monitor(M, F, A, Timeout) when is_atom(M), is_atom(F), is_list(A) ->
sync_start_monitor(spawn_mon(M, F, A), Timeout).
-doc """
Starts a new process synchronously. Spawns the process and waits for it to
start. A monitor is atomically set on the newly spawned process.
Besides setting a monitor on the spawned process this function behaves like
[start/5](`start/5`).
The return value is `{Ret, Mon}` where `Ret` corresponds to the `Ret` argument
in the call to `init_ack/1,2` or `init_fail/2,3`, and `Mon` is the monitor
reference of the monitor that has been set up.
If this function returns due to the spawned process exiting, that is returns any
error value, a `'DOWN'` message will be delivered to the calling process, also
when this function times out and kills the spawned process.
> #### Note {: .info }
>
> Using spawn option `monitor` is not allowed. It causes the function to fail
> with reason `badarg`.
>
> Using spawn option `link` will set a link to the spawned process, just like
> [start_link/3,4,5](`start_link/3`).
""".
-doc(#{since => <<"OTP 23.0">>}).
-spec start_monitor(Module, Function, Args, Time, SpawnOpts) -> {Ret, Mon} when
Module :: module(),
Function :: atom(),
Args :: [term()],
Time :: timeout(),
SpawnOpts :: [start_spawn_option()],
Mon :: reference(),
Ret :: term() | {error, Reason :: term()}.
start_monitor(M,F,A,Timeout,SpawnOpts) when is_atom(M),
is_atom(F),
is_list(A) ->
?VERIFY_NO_MONITOR_OPT(M, F, A, Timeout, SpawnOpts),
sync_start_monitor(
?MODULE:spawn_opt(M, F, A, [monitor|SpawnOpts]), Timeout).
sync_start_monitor({Pid, Ref}, Timeout) ->
receive
{ack, Pid, Return} ->
{Return, Ref};
{nack, Pid, Return} ->
flush_EXIT(Pid),
self() ! await_DOWN(Pid, Ref),
{Return, Ref};
{'DOWN', Ref, process, Pid, Reason} = Down ->
flush_EXIT(Pid),
self() ! Down,
{{error, Reason}, Ref}
after Timeout ->
kill_flush_EXIT(Pid),
self() ! await_DOWN(Pid, Ref),
{{error, timeout}, Ref}
end.
%% We regard the existence of an {'EXIT', Pid, _} message
%% as proof enough that there was a link that fired and
%% we had process_flag(trap_exit, true),
%% so the message should be flushed.
%% It is the best we can do.
%%
%% After an unlink(Pid) an {'EXIT', Pid, _} link message
%% cannot arrive so receive after 0 will work,
flush_EXIT(Pid) ->
unlink(Pid),
receive {'EXIT', Pid, _} -> ok after 0 -> ok end.
kill_flush_EXIT(Pid) ->
%% unlink/1 has to be called before exit/2
%% or we might be killed by the link
unlink(Pid),
exit(Pid, kill),
receive {'EXIT', Pid, _} -> ok after 0 -> ok end.
await_DOWN(Pid, Ref) ->
receive
{'DOWN', Ref, process, Pid, _} = Down ->
Down
end.
-doc """
This function must only be used by a process that has been started by a
[`start[_link|_monitor]/3,4,5`](`start/5`) function. It tells `Parent` that the
process has initialized itself and started.
Function [`init_ack/1`](`init_ack/1`) uses the parent value previously stored by
the start function used.
If neither this function nor [`init_fail/2,3`](`init_fail/3`) is called by the
started process, the start function returns an error tuple when the started
process exits, or when the start function time-out (if used) has passed, see
[`start/3,4,5`](`start/5`).
> #### Warning {: .warning }
>
> Do not use this function to return an error indicating that the process start
> failed. When doing so the start function can return before the failing process
> has exited, which may block VM resources required for a new start attempt to
> succeed. Use [`init_fail/2,3`](`init_fail/3`) for that purpose.
The following example illustrates how this function and `proc_lib:start_link/3`
are used:
```erlang
-module(my_proc).
-export([start_link/0]).
-export([init/1]).
start_link() ->
proc_lib:start_link(my_proc, init, [self()]).
init(Parent) ->
case do_initialization() of
ok ->
proc_lib:init_ack(Parent, {ok, self()});
{error, Reason} ->
exit(Reason)
end,
loop().
...
```
""".
-spec init_ack(Parent, Ret) -> 'ok' when
Parent :: pid(),
Ret :: term().
init_ack(Parent, Return) ->
Parent ! {ack, self(), Return},
ok.
-doc """
Equivalent to [`init_ack(Parent, Ret)`](`init_ack/2`) where `Parent` is
the process that called `start/5`.
""".
-spec init_ack(Ret) -> 'ok' when
Ret :: term().
init_ack(Return) ->
[Parent|_] = get('$ancestors'),
init_ack(Parent, Return).
-doc """
This function must only be used by a process that has been started by a
[`start[_link|_monitor]/3,4,5`](`start/3`) function. It tells `Parent` that the
process has failed to initialize, and immediately raises an exception according
to `Exception`. The start function then returns `Ret`.
See `erlang:raise/3` for a description of `Class`, `Reason` and `Stacktrace`.
> #### Warning {: .warning }
>
> Do not consider catching the exception from this function. That would defeat
> its purpose. A process started by a [`start[_link|_monitor]/3,4,5`](`start/3`)
> function should end in a value (that will be ignored) or an exception that
> will be handled by this module. See [Description](`m:proc_lib`).
If neither this function nor [`init_ack/1,2`](`init_ack/1`) is called by the
started process, the start function returns an error tuple when the started
process exits, or when the start function time-out (if used) has passed, see
[`start/3,4,5`](`start/3`).
The following example illustrates how this function and `proc_lib:start_link/3`
can be used:
```erlang
-module(my_proc).
-export([start_link/0]).
-export([init/1]).
start_link() ->
proc_lib:start_link(my_proc, init, [self()]).
init(Parent) ->
case do_initialization() of
ok ->
proc_lib:init_ack(Parent, {ok, self()});
{error, Reason} = Error ->
proc_lib:init_fail(Parent, Error, {exit, normal})
end,
loop().
...
```
""".
-doc(#{since => <<"OTP 26.0">>}).
-spec init_fail(Parent :: pid(), Return :: term(), Exception :: exception()) -> no_return().
init_fail(Parent, Return, Exception) ->
_ = Parent ! {nack, self(), Return},
case Exception of
{error, Reason} ->
erlang:error(Reason);
{exit, Reason} ->
erlang:exit(Reason);
{throw, Reason} ->
erlang:throw(Reason);
{Class, Reason, Stacktrace} ->
erlang:error(
erlang:raise(Class, Reason, Stacktrace),
[Parent, Return, Exception])
end.
-doc """
Equivalent to [`init_fail(Parent, Return, Exception)`](`init_fail/3`) where
`Parent` is the process that called `start/5`.
""".
-doc(#{since => <<"OTP 26.0">>}).
-spec init_fail(Return :: term(), Exception :: exception()) -> no_return().
init_fail(Return, Exception) ->
[Parent|_] = get('$ancestors'),
init_fail(Parent, Return, Exception).
%% -----------------------------------------------------
%% Fetch the initial call of a proc_lib spawned process.
%% -----------------------------------------------------
-doc """
Extracts the initial call of a process that was started using one of the spawn
or start functions in this module. `Process` can either be a pid, an integer
tuple (from which a pid can be created), or the process information of a process
`Pid` fetched through an `erlang:process_info(Pid)` function call.
> #### Note {: .info }
>
> The list `Args` no longer contains the arguments, but the same number of atoms
> as the number of arguments; the first atom is `'Argument__1'`, the second
> `'Argument__2'`, and so on. The reason is that the argument list could waste a
> significant amount of memory, and if the argument list contained funs, it
> could be impossible to upgrade the code for the module.
>
> If the process was spawned using a fun, [`initial_call/1`](`initial_call/1`)
> no longer returns the fun, but the module, function for the local function
> implementing the fun, and the arity, for example,
> `{some_module,-work/3-fun-0-,0}` (meaning that the fun was created in function
> `some_module:work/3`). The reason is that keeping the fun would prevent code
> upgrade for the module, and that a significant amount of memory could be
> wasted.
""".
-spec initial_call(Process) -> {Module, Function, Args} | 'false' when
Process :: dict_or_pid(),
Module :: module(),
Function :: atom(),
Args :: [atom()].
initial_call(DictOrPid) ->
case raw_initial_call(DictOrPid) of
{M,F,A} ->
{M,F,make_dummy_args(A, [])};
false ->
false
end.
make_dummy_args(0, Acc) ->
Acc;
make_dummy_args(N, Acc) ->
Arg = list_to_atom("Argument__" ++ integer_to_list(N)),
make_dummy_args(N-1, [Arg|Acc]).
%% -----------------------------------------------------
%% Translate the '$initial_call' to some useful information.
%% However, the arguments are not returned here; only the
%% arity of the initial function.
%% This function is typically called from c:i() and c:regs().
%% -----------------------------------------------------
-doc """
This function is used by functions `\c:i/0` and `\c:regs/0` to present process
information.
This function extracts the initial call of a process that was started using one
of the spawn or start functions in this module, and translates it to more useful
information. `Process` can either be a pid, an integer tuple (from which a pid
can be created), or the process information of a process `Pid` fetched through
an `erlang:process_info(Pid)` function call.
If the initial call is to one of the system-defined behaviors such as
`gen_server` or `gen_event`, it is translated to more useful information. If a
`gen_server` is spawned, the returned `Module` is the name of the callback
module and `Function` is `init` (the function that initiates the new server).
A `supervisor` and a `supervisor_bridge` are also `gen_server` processes. To
return information that this process is a supervisor and the name of the
callback module, `Module` is `supervisor` and `Function` is the name of the
supervisor callback module. `Arity` is `1`, as the `init/1` function is called
initially in the callback module.
By default, `{proc_lib,init_p,5}` is returned if no information about the
initial call can be found. It is assumed that the caller knows that the process
has been spawned with the `proc_lib` module.
""".
-spec translate_initial_call(Process) -> {Module, Function, Arity} when
Process :: dict_or_pid(),
Module :: module(),
Function :: atom(),
Arity :: byte().
translate_initial_call(DictOrPid) ->
case raw_initial_call(DictOrPid) of
{_,_,_}=MFA ->
MFA;
false ->
{?MODULE,init_p,5}
end.
%% -----------------------------------------------------
%% [get] set_label/1
%% Add and fetch process id's to aid in debugging
%% -----------------------------------------------------
-doc """
Set a label for the current process. The primary purpose is to aid in debugging
unregistered processes. The process label can be used in tools and crash reports
to identify processes but it doesn't have to be unique or an atom, as a
registered name needs to be. The process label can be any term, for example
`{worker_process, 1..N}`.
Use [`proc_lib:get_label/1`](`get_label/1`) to lookup the process description.
""".
-doc(#{since => <<"OTP 27.0">>}).
-spec set_label(Label) -> ok when
Label :: term().
set_label(Label) ->
put('$process_label', Label),
ok.
-doc """
Returns either `undefined` or the label for the process Pid set with
[`proc_lib:set_label/1`](`set_label/1`).
""".
-doc(#{since => <<"OTP 27.0">>}).
-spec get_label(Pid) -> undefined | term() when
Pid :: pid().
get_label(Pid) ->
case Pid == self() of
true ->
get('$process_label');
false ->
try get_process_info(Pid, {dictionary, '$process_label'}) of
{process_label, Id} -> Id;
_ -> undefined
catch _:_ -> %% Old Node
undefined
end
end.
%% -----------------------------------------------------
%% Fetch the initial call information exactly as stored
%% in the process dictionary.
%% -----------------------------------------------------
raw_initial_call({X,Y,Z}) when is_integer(X), is_integer(Y), is_integer(Z) ->
raw_initial_call(c:pid(X,Y,Z));
raw_initial_call(Pid) when is_pid(Pid) ->
case get_dictionary(Pid, '$initial_call') of
{_,_,_}=MFA -> MFA;
_ -> false
end;
raw_initial_call(ProcInfo) when is_list(ProcInfo) ->
case lists:keyfind({dictionary, '$initial_call'}, 1, ProcInfo) of
{{dictionary,_}, {_,_,_}=MFA} ->
MFA;
false ->
case lists:keyfind(dictionary, 1, ProcInfo) of
{dictionary,Dict} ->
case lists:keyfind('$initial_call', 1, Dict) of
{_,{_,_,_}=MFA} ->
MFA;
_ ->
false
end;
_ ->
false
end
end.
%% -----------------------------------------------------
%% Translate the initial call to some useful information.
%% -----------------------------------------------------
trans_init(gen,init_it,[gen_server,_,_,supervisor,{_,Module,_},_]) ->
{supervisor,Module,1};
trans_init(gen,init_it,[gen_server,_,_,_,supervisor,{_,Module,_},_]) ->
{supervisor,Module,1};
trans_init(gen,init_it,[gen_server,_,_,supervisor_bridge,[Module|_],_]) ->
{supervisor_bridge,Module,1};
trans_init(gen,init_it,[gen_server,_,_,_,supervisor_bridge,[Module|_],_]) ->
{supervisor_bridge,Module,1};
trans_init(gen,init_it,[gen_event|_]) ->
{gen_event,init_it,6};
trans_init(gen,init_it,[_GenMod,_,_,Module,_,_]) when is_atom(Module) ->
{Module,init,1};
trans_init(gen,init_it,[_GenMod,_,_,_,Module|_]) when is_atom(Module) ->
{Module,init,1};
trans_init(M, F, A) when is_atom(M), is_atom(F) ->
{M,F,length(A)}.
%% -----------------------------------------------------
%% Generate a crash report.
%% -----------------------------------------------------
crash_report(exit, normal, _, _) -> ok;
crash_report(exit, shutdown, _, _) -> ok;
crash_report(exit, {shutdown,_}, _, _) -> ok;
crash_report(Class, Reason, StartF, Stacktrace) ->
?LOG_ERROR(#{label=>{proc_lib,crash},
report=>[my_info(Class, Reason, StartF, Stacktrace),
linked_info(self())]},
#{domain=>[otp,sasl],
report_cb=>fun proc_lib:report_cb/2,
logger_formatter=>#{title=>"CRASH REPORT"},
error_logger=>#{tag=>error_report,type=>crash_report}}).
my_info(Class, Reason, [], Stacktrace) ->
my_info_1(Class, Reason, Stacktrace);
my_info(Class, Reason, StartF, Stacktrace) ->
[{initial_call, StartF}|
my_info_1(Class, Reason, Stacktrace)].
my_info_1(Class, Reason, Stacktrace) ->
Keys = [registered_name, dictionary, message_queue_len,
links, trap_exit, status, heap_size, stack_size, reductions],
PInfo = get_process_info(self(), Keys),
{dictionary, Dict} = lists:keyfind(dictionary,1,PInfo),
[{pid, self()},
lists:keyfind(registered_name,1,PInfo),
{process_label, get_label(self())},
{error_info, {Class,Reason,Stacktrace}},
{ancestors, get_ancestors()},
lists:keyfind(message_queue_len,1,PInfo),
get_messages(self()),
lists:keyfind(links, 1, PInfo),
{dictionary, cleaned_dict(Dict)},
lists:keyfind(trap_exit, 1, PInfo),
lists:keyfind(status, 1, PInfo),
lists:keyfind(heap_size, 1, PInfo),
lists:keyfind(stack_size, 1, PInfo),
lists:keyfind(reductions, 1, PInfo)
].
%% The messages and the dictionary are possibly limited too much if
%% some error handles output the messages or the dictionary using ~P
%% or ~W with depth greater than the depth used here (the depth of
%% control characters P and W takes precedence over the depth set by
%% application variable error_logger_format_depth). However, it is
%% assumed that all report handlers call proc_lib:format().
get_messages(Pid) ->
Messages = get_process_messages(Pid),
{messages, error_logger:limit_term(Messages)}.
get_process_messages(Pid) ->
Depth = error_logger:get_format_depth(),
case Pid =/= self() orelse Depth =:= unlimited of
true ->
{messages, Messages} = get_process_info(Pid, messages),
Messages;
false ->
%% If there are more messages than Depth, garbage