有没类似erlang:list_to_pid的erlang:list_to_port函数

51 views
Skip to first unread message

filebat Mark

unread,
Jun 2, 2012, 11:03:28 AM6/2/12
to erlang...@googlegroups.com
hi all

当open_port创建一个Port时, 可以打印出Port相关信息。
如果程序出问题时, 通过erlang shell连进去trouble shooting时, 如何根据该Port id, 得到对应的Port呢?

erlang:list_to_pid,可以通过pid找到对应的Process, 对于erlang port有吗?


--
Thanks & Regards

Denny Zhang

Wei Cao

unread,
Jun 3, 2012, 11:12:09 PM6/3/12
to erlang...@googlegroups.com
erlang没提供,有两个方法自己写:

一个是从erlang:ports()返回的列表里查找
-module(no_to_port).
-export([impl1/2, impl2/2]).

impl1(Part1, Part2)->
    [Port] = lists:filter(fun(P)-> proplists:get_value('id',erlang:port_info(P)) =:= Part1 * 256 + Part2  end, erlang:ports()),
    Port.

另一个是直接拼出表示port的binary,再转成term

impl2(Part1, Part2)->
    Node = list_to_binary(atom_to_list(node())),
    Size = byte_size(Node),
    NO = Part1 * 256 + Part2,
    binary_to_term(<<131,102,100, Size:16, Node/binary, NO:32, 0>>).

运行结果
wei@t-mingsong:~/erl/test$ erl
Erlang R15A (erts-5.9) [source] [64-bit] [smp:2:2] [rq:2] [async-threads:0] [kernel-poll:false]

Eshell V5.9  (abort with ^G)
1> no_to_port:impl1(0,1).
#Port<0.1>
2> no_to_port:impl2(0,1).
#Port<0.1>

--

Best,

Wei Cao

Yu Feng

unread,
Jun 4, 2012, 3:57:45 AM6/4/12
to erlang...@googlegroups.com, erlang...@googlegroups.com
专业呀

Sent from my iPhone

filebat Mark

unread,
Jun 4, 2012, 6:21:15 AM6/4/12
to Yu Feng, erlang...@googlegroups.com
强!!

Yu Feng <mryu...@gmail.com>编写:

Zheng Zhibin

unread,
Jun 11, 2012, 3:21:20 AM6/11/12
to erlang...@googlegroups.com
是挺专业的^_^

不过,方法二需要注意一些问题。

Thanks and regards,
==========================
郑智斌(Witeman Zheng)
广州安浩软件科技有限公司
研发总监
公司电邮:wit...@iconventure.com
手机:+86 186 2020 2930
QQ:19653403
==========================

在 2012-6-4,下午3:57, Yu Feng 写道:

专业呀

Sent from my iPhone

On 2012-6-4, at 上午11:12, Wei Cao <cyg...@gmail.com> wrote:

erlang没提供,有两个方法自己写:

一个是从erlang:ports()返回的列表里查找
-module(no_to_port).
-export([impl1/2, impl2/2]).

impl1(Part1, Part2)->
    [Port] = lists:filter(fun(P)-> proplists:get_value('id',erlang:port_info(P)) =:= Part1 * 256 + Part2  end, erlang:ports()),
    Port.

另一个是直接拼出表示port的binary,再转成term

impl2(Part1, Part2)->
    Node = list_to_binary(atom_to_list(node())),
    Size = byte_size(Node),
    NO = Part1 * 256 + Part2,
    binary_to_term(<<131,102,100, Size:16, Node/binary, NO:32, 0>>).

第一个字节是VERSION_MAGIC,不同的Erlang版本是不同的,4.2是130,之后到现在的是131,以后说不定会改成其他。

Feng Yu

unread,
Jun 11, 2012, 5:23:56 AM6/11/12
to erlang...@googlegroups.com
hack手段总是不是首选。

专注高性能容错分布式服务器的研究和实现
http://blog.yufeng.info
Reply all
Reply to author
Forward
0 new messages