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"
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>
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With