Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transform Process ID (`pid`) in Elixir to Tuple or string; Parse `pid` to other types

Tags:

elixir

How do I transform a Process ID PID into a tuple or string?

For example, let's say I have a PID named my_pid

iex(1)> my_pid
#PID<0.1692.0>

How would I transform the PID ID to a tuple or a string to get either?

{ 0, 1692, 0 }

or

"0.1692.0"
like image 449
DogEatDog Avatar asked Jan 26 '26 23:01

DogEatDog


2 Answers

You are after :erlang.pid_to_list/1 and :erlang.list_to_pid/1 functions.

list = self() |> :erlang.pid_to_list()
#⇒ [60, 48, 46, 49, 49, 48, 46, 48, 62]
to_string(list)
#⇒ "<0.110.0>"
list |> List.delete_at(0) |> List.delete_at(-1) |> to_string()
#⇒ "0.110.0"

The advantage of this approach is that it’s convertible

:erlang.list_to_pid(list)
#⇒ #PID<0.110.0>
like image 120
Aleksei Matiushkin Avatar answered Jan 28 '26 11:01

Aleksei Matiushkin


step by step:

pid = self()         # gets shells pid e.g. #PID<0.105.0>

a = "#{inspect pid}" # gives the string "#PID<0.105.0>"

b = String.slice a, 5,100 # remove the prefix #PID<
c = String.trim b, ">"    # remove the postfix >
d = String.split c, "."   # create list of strings: ["0", "105", "0"]

e = Enum.map( d ,fn x -> String.to_integer(x) end) # converts to a list of integers
f = Enum.join(e, " ")

result: "0 105 0"

like image 20
GavinBrelstaff Avatar answered Jan 28 '26 11:01

GavinBrelstaff