Erlang經常使用代碼段

  • 十六進制字符串轉爲二進制app

    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。選項有oop

    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命令獲得的消耗的內存ui

    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命令獲得的消耗的內存spa

    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的核數code

    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命令獲得的虛擬內存消耗orm

    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命令獲得的虛擬內存消耗server

```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運行時的進程信息
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'消息。

相關文章
相關標籤/搜索