【原创】调用 proc_lib:spawn/1 和 erlang:spawn/1 有什么区别

简介:
在《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 中有如下说明  
?
1
2
3
4
5
6
-module(proc_lib).
 
%% 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.

而 proc_lib:spawn/1 的实现为  
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
spawn(F) when is_function(F) ->
     Parent = get_my_name(),
     Ancestors = get_ancestors(),
     erlang:spawn(?MODULE, init_p, [Parent,Ancestors,F]).
 
init_p(Parent, Ancestors, Fun) when is_function(Fun) ->
     put( '$ancestors' , [Parent|Ancestors]),
     {module,Mod} = erlang:fun_info(Fun, module),
     {name,Name} = erlang:fun_info(Fun, name),
     {arity,Arity} = erlang:fun_info(Fun, arity),
     put( '$initial_call' , {Mod,Name,Arity}),
     try
    Fun()
     catch
    Class:Reason ->
    exit_p(Class, Reason)
     end.
      可以看出,其比通常调用 erlang:spawn/1 会多出对祖先信息(Parent 和 Ancestors)和函数相关信息(module+name+arity)的处理,而这些信息是监督树所需要的。  
目录
相关文章
Cannot lock pid file /usr/local/freeswitch/run/freeswitch.pid.
Cannot lock pid file /usr/local/freeswitch/run/freeswitch.pid.
187 0
|
3月前
|
物联网 持续交付 开发工具
RT-Thread 学习-Env开发环境搭建(一)
RT-Thread 学习-Env开发环境搭建(一)
51 0
RT-Thread 学习-Env开发环境搭建(一)
|
PHP Windows
windows下 Call to undefined function posix_getpid() in ……\Workerman\Worker.php 的解决方法
windows下 Call to undefined function posix_getpid() in ……\Workerman\Worker.php 的解决方法
125 0
windows下 Call to undefined function posix_getpid() in ……\Workerman\Worker.php 的解决方法
|
12月前
|
持续交付 开发工具 git
【RT-Thread env 工具安装】
【RT-Thread env 工具安装】
144 0
|
iOS开发 MacOS Python
解决 Sourcetree 报错 Couldn't posix_spawn: error 2 问题
解决 Sourcetree 报错 Couldn't posix_spawn: error 2 问题
1243 0
解决 Sourcetree 报错 Couldn't posix_spawn: error 2 问题
|
Unix 应用服务中间件 Apache
FastCGI与spawn-fcg简介
FastCGI与spawn-fcg简介
173 0
FastCGI与spawn-fcg简介
解决spawn-fcgi:child exited with: 127报错
解决spawn-fcgi:child exited with: 127报错
245 0
解决spawn-fcgi:child exited with: 127报错
|
JavaScript 网络协议 Shell
在nodejs中创建child process
在nodejs中创建child process
|
JavaScript
Nodejs中process.cwd()与__dirname的区别
首先,上官方解释。 => process.cwd(): The process.cwd() method returns the current working directory of theNode.js process. 上面的意思就是,process.cwd()返回的是当前Node.js进程执行时的工作目录。
3793 0

热门文章

最新文章