Erlang常用代码段
十六进制字符串转为二进制
hex_to_bin(Bin) ->
hex2bin(Bin). hex2bin(Bin) when is_binary(Bin) ->
hex2bin(binary_to_list(Bin));
hex2bin([]) ->
<<>>;
hex2bin([X, Y | Rest]) ->
<<(erlang:list_to_integer([X], 16) * 16 + erlang:list_to_integer([Y], 16)):8, (hex2bin(Rest))/binary>>.
二进制转为十六进制字符串
bin2hex(B) ->
bin2hex(B, lower). bin2hex(B, LowerOrUpper) when is_binary(B) ->
bin2hex(binary_to_list(B), LowerOrUpper);
bin2hex(L, upper) ->
LH0 = lists:map(fun(X) -> erlang:integer_to_list(X, 16) end, L),
LH = lists:map(fun([X, Y]) -> [X, Y]; ([X]) -> [$0, X] end, LH0),
lists:flatten(LH);
bin2hex(B, lower) ->
H = bin2hex(B, upper),
string:to_lower(H).
反编译代码
有时候线上出问题的时候,需要查看线上运行的代码,这时候就用到反编译了。
decompile(Mod) ->
{ok, {_, [{abstract_code, {_, AC}}]}} = beam_lib:chunks(code:which(Mod), [abstract_code]),
try
io:format("~s~n", [erl_prettypr:format(erl_syntax:form_list(AC))])
catch
io:format("~ts~n", [erl_prettypr:format(erl_syntax:form_list(AC))])
end.
分裂进程
erlang分裂进程的函数是erlang:spawn。选项有spawn(Fun) -> pid()
spawn(Node, Fun) -> pid() %如果Node不存在,返回一个无用的pid
spawn(Module, Function, Args) -> pid()
spawn(Node, Module, Function, Args) -> pid()
spawn_link(Fun) -> pid()
spawn_link(Node, Fun) -> pid()
spawn_link(Module, Function, Args) -> pid()
spawn_link(Node, Module, Function, Args) -> pid()
spawn_monitor(Fun) -> {pid(), reference()}
spawn_monitor(Module, Function, Args) -> {pid(), reference()}
spawn_opt(Fun, Options) -> pid() | {pid(), reference()}
spawn_opt(Node, Fun, Options) -> pid() | {pid(), reference()}
spawn_opt(Module, Function, Args, Options) -> pid() | {pid(), reference()}
spawn_opt(Node, Module, Function, Args, Options) -> pid() | {pid(), reference()}
Options = [Option]
Option =
link |
monitor |
{priority, Level :: priority_level()} |
{fullsweep_after, Number :: integer() >= 0} |
{min_heap_size, Size :: integer() >= 0} |
{min_bin_vheap_size, VSize :: integer() >= 0}
priority_level() = low | normal | high | max
+ link: 父进程与子进程建立连接
+ monitor: 父进程监控子进程
+ {priority, Level}: 设置新的进程的优先级。等价于在新进程中执行process_flag(priority, Level)。区别在于,spawn的时候设置优先级,优先级会在进程被选择运行之前就设置好了。
+ {fullsweep_after, Number}:只是用在调整性能上。Erlang的运行系统,使用的是分代的垃圾回收机制。用一个『old heap』保存至少存活了一个垃圾回收周期的数据,当old heap空间不够时,就会执行垃圾回收。
+ {min_heap_size, Size},只是用在调整性能上。设置heap的最小size,单位是word。将这个值设置的比系统默认的大的话,会加速一些进程运行,因为会减少垃圾回收的执行次数。但是太大会导致内存不够,减慢系统运行。
+ {min_bin_vheap_size, VSize},只是用在调整性能上。
+ 交叉引用工具:xref。xref通过分析函数的调用和定义,发现函数、模块、应用和版本之间的依赖关系。这个工具可以帮助查看是否有函数名输入错误。在用rebar打包时,可以用rebar xref执行。
+ 获得ps命令得到的消耗的内存
```erlang
get_ps_real_memory() ->
Cmd = "pid=`echo $$`;p=`ps -ef | awk -v pid=$pid '$2 == pid {print $3}'`;mem=`ps -o rss -p $p | grep -v RSS`;r=$(($mem/1024));echo $r",
os:cmd(Cmd),
Result = os:cmd(Cmd),
string:substr(Result, 1, length(Result) - 1).
```
+ 获得top命令得到的消耗的内存
```erlang
get_top_real_memory() ->
Cmd = "pid=`echo $$`;p=`ps -ef | awk -v pid=$pid '$2 == pid {print $3}'`;mem=`cat /proc/$p/stat | awk '{print $24}'`;r=$(($mem*4096/1024/1024));echo $r",
Result = os:cmd(Cmd),
case length(Result) > 1 of
true ->
string:substr(Result, 1, length(Result) -1);
false ->
0
end.
```
+ 获得当前cpu的核数
```erlang
get_cpu_count() ->
Cmd = "cat /proc/cpuinfo | grep processor | wc -l",
R = os:cmd(Cmd),
case string:to_integer(R) of
{Count, _} when is_integer(Count) -> Count;
{error, _} -> 0
end.
```
+ 获得ps命令得到的虚拟内存消耗
```erlang
get_ps_virtual_memory() ->
Cmd = "pid=`echo $$`;p=`ps -ef | awk -v pid=$pid '$2 == pid {print $3}'`;mem=`ps -o vsz -p $p | grep -v VSZ`;r=$(($mem/1024));echo $r",
Result = os:cmd(Cmd),
string:substr(Result, 1, length(Result) - 1).
```
+获得top命令得到的虚拟内存消耗
```erlang
get_top_virtual_memory() ->
Cmd = "pid=`echo $$`;p=`ps -ef | awk -v pid=$pid '$2 == pid {print $3}'`;mem=`cat /proc/$p/stat | awk '{print $24}'`;r=$(($mem*4096/1024/1024));echo $r",
Result = os:cmd(Cmd),
case length(Result) > 1 of
true ->
string:substr(Result, 1, length(Result) - 1);
false ->
0
end.
```
+ 获得erlang运行时的进程信息
```erlang
process_infos() ->
filelib:ensure_dir("./log/"),
File = "./log/processes_infos.log",
{ok, Fd} = file:open(File, [write, raw, binary, append]),
Fun = fun(Pi) ->
Info = io_lib:format("=>~p \n\n",[Pi]),
case filelib:is_file(File) of
true -> file:write(Fd, Info);
false ->
file:close(Fd),
{ok, NewFd} = file:open(File, [write, raw, binary, append]),
file:write(NewFd, Info)
end,
timer:sleep(20)
end,
[Fun(erlang:process_info(P)) || P <- erlang:processes()].
- eralng gen_server:call
这是一个同步调用,pid1通过erlang:send()发送给pid2消息后,receive等待返回,这时候pid1处于阻塞状态。pid2是一个gen_server行为模式的进程,loop函数接收到消息后,进行相应处理,并返回。
- gen_server:cast
直接用erlang:send发送'$gen_cast'消息。
Erlang常用代码段的更多相关文章
- PyTorch常用代码段整理合集
PyTorch常用代码段整理合集 转自:知乎 作者:张皓 众所周知,程序猿在写代码时通常会在网上搜索大量资料,其中大部分是代码段.然而,这项工作常常令人心累身疲,耗费大量时间.所以,今天小编转载了知乎 ...
- Java常用代码段 - 未完待续
记录一些自己写项目常用的代码段. 格式化常用日期格式 Date date = new Date(System.currentTimeMillis()); DateFormat d3 = DateFor ...
- PyTorch 常用代码段整理
基础配置 检查 PyTorch 版本 torch.__version__ # PyTorch version torch.version.cuda ...
- JavaScript常用代码段
总结一下在各种地方看到的还有自己使用的一些实用代码 1)区分IE和非IE浏览器 if(!+[1,]){ alert("这是IE浏览器"); } else{ alert(" ...
- C#获取本地IP地址[常用代码段]
获得当前机器的IP代码,假设本地主机为单网卡 string strHostName = Dns.GetHostName(); //得到本机的主机名 IPHostEntry ipEntry = Dns. ...
- php常用代码段
点击换验证码 <a href=" src="{:U('Reglog/vcode')}" /></a> TP上一条下一条 $prev=$artica ...
- SQL常用代码段
--STUFF 函数将字符串插入另一字符串.它在第一个字符串中从开始位置删除指定长度的字符:然后将第二个字符串插入第一个字符串的开始位置. STUFF ( character_expression , ...
- PHP常用代码段:
1.PHP加密解密 function encryptDecrypt($key, $string, $decrypt){ if($decrypt){ $decrypted ...
- php 常用代码段
1.写文件 $fp = fopen("jsapi_ticket.json", "w+"); fwrite($fp, $str); fclose($fp); 2. ...
随机推荐
- SQL Server 索引列的顺序——真的没关系吗
原文:SQL Server 索引列的顺序--真的没关系吗 翻译自:http://www.mssqltips.com/sqlservertip/2718/sql-server-index-column- ...
- Cocos2d-x Auto-batching 浅浅的”深入分析”
Auto-batching是Cocos2d-x3.0新增的特性,目的是为了代替SpriteBatchNode,完毕渲染的批处理,提高绘制效率. 至于它有什么特点,能够看看官方文档,这里主要想探讨Aut ...
- spring mvc中实现csrf安全防御简记
1.csrf是什么 csrf全称是Cross-site request forgery,http://en.wikipedia.org/wiki/Csrf 危害:使受害用户在不经意间执行了不是用户意愿 ...
- 走向DBA[MSSQL篇] 详解游标
原文:走向DBA[MSSQL篇] 详解游标 前篇回顾:上一篇虫子介绍了一些不常用的数据过滤方式,本篇详细介绍下游标. 概念 简单点说游标的作用就是存储一个结果集,并根据语法将这个结果集的数据逐条处理. ...
- 并发队列ConcurrentLinkedQueue和阻塞队列LinkedBlockingQueue用法(转)
在Java多线程应用中,队列的使用率很高,多数生产消费模型的首选数据结构就是队列(先进先出).Java提供的线程安全的Queue可以分为阻塞队列和非阻塞队列,其中阻塞队列的典型例子是BlockingQ ...
- 章节2:SQL之多表连接
原文:章节2:SQL之多表连接 Sql的多表连接关系有:内连接.外连接和交叉连接. 先建立两个用于演示的表: TB_Characters: Id Character 1 内向 2 外向 3 中性性格 ...
- Flux demo
Flux demo Introduction flux应用架构如下图所示,本文并不是讲述怎么立即做一个酷炫的应用,而是讲述如何依照这种框架,来进行代码的组织.我们先把这个流程转述为文字:抛开与webA ...
- 自制Https证书并在Spring Boot和Nginx中使用(转)
白话Https一文中, 介绍了Https存在的目的和工作原理,但多是偏向于原理性的介绍,本文介绍如何一步一步自制一个能够通过浏览器认证的Https证书,并讲解在Spring Boot环境和Nginx环 ...
- PHP图片等比缩放,并添加Logo水印特定代码和盯
<? php //PHP图片等比缩放,并添加Logo水印 --->百度 "美日汇" /** * 等比缩放函数(以保存的方式实现) * @param string $pi ...
- C#后台利用正则表达式查找匹配字符
/// <summary> /// 发送短信 系统固化短信 /// </summary> /// <param name=&qu ...