在《erlang otp 设计原则》中的 “sys与proc_lib” 一节中有如下描述:
模块 proc_lib 中的函数可以用于实现一种特殊进程,遵照 otp 设计原则,但不使用标准行为。它们也可以用于实现用户自定义的(非标准)行为。
怎样算是符合 otp 设计原理而又不使用标准行为的 “特殊进程”呢?
以一种可以让进程放入监督树的方式启动;
支持 sys 的调试功能;
关注系统消息 。
什么是系统消息?
系统消息是用于监督树中的、带有特殊含义的消息。典型的系统消息有跟踪输出的请求、挂起和恢复进程执行的请求(用于发布处理中)。基于标准行为模式实现的进程会自动处理这些消息。
如何使用 proc_lib 中的函数创建进程?
用 proc_lib 模块中存在的若干函数来启动进程,例如异步启动的 spawn_link/3,4 以及同步启动的 start_link/3,4,5 。
使用这些函数中的任何一个启动的进程都会储存监督树所必须的信息。
当使用 proc_lib:start_link 以同步方式启动进程时,调用进程直到 proc_lib:init_ack 被调用后才返回,所以必须成对使用。
在 stdlib\src\proc_lib.erl 中有如下说明
<a href="http://my.oschina.net/moooofly/blog/281997#">?</a>
1
2
3
4
5
6
<code>-module(proc_lib).</code>
<code>%% this module is used to</code><code>set</code> <code>some initial information</code>
<code>%%</code><code>in</code> <code>each created process.</code>
<code>%% then a process terminates the reason is checked and</code>
<code>%% a crash report is generated</code><code>if</code> <code>the reason was not expected.</code>
而 proc_lib:spawn/1 的实现为
7
8
9
10
11
12
13
14
15
16
17
<code>spawn(f) when is_function(f) -></code>
<code> </code><code>parent = get_my_name(),</code>
<code> </code><code>ancestors = get_ancestors(),</code>
<code> </code><code>erlang:spawn(?module, init_p, [parent,ancestors,f]).</code>
<code>init_p(parent, ancestors, fun) when is_function(fun) -></code>
<code> </code><code>put(</code><code>'$ancestors'</code><code>, [parent|ancestors]),</code>
<code> </code><code>{module,mod} = erlang:fun_info(fun, module),</code>
<code> </code><code>{name,name} = erlang:fun_info(fun, name),</code>
<code> </code><code>{arity,arity} = erlang:fun_info(fun, arity),</code>
<code> </code><code>put(</code><code>'$initial_call'</code><code>, {mod,name,arity}),</code>
<code> </code><code>try</code>
<code> </code><code>fun()</code>
<code> </code><code>catch</code>
<code> </code><code>class:reason -></code>
<code> </code><code>exit_p(class, reason)</code>
<code> </code><code>end.</code>
可以看出,其比通常调用 erlang:spawn/1 会多出对祖先信息(parent 和 ancestors)和函数相关信息(module+name+arity)的处理,而这些信息是监督树所需要的。