Skip to content

Instantly share code, notes, and snippets.

@dbuduev
Last active August 3, 2016 11:15
Show Gist options
  • Save dbuduev/b1a6cbf5a3371a0956d1b4422c57fa19 to your computer and use it in GitHub Desktop.
Save dbuduev/b1a6cbf5a3371a0956d1b4422c57fa19 to your computer and use it in GitHub Desktop.
defmodule MySpawn do
def spawn_monitor(mod, func, args) do
root_pid = self()
spawn(fn ->
{pid, ref} = :erlang.spawn_monitor(mod, func, args)
send(root_pid, pid)
start_time = :calendar.local_time
receive do
{:DOWN, ^ref, :process, ^pid, why} -> print_on_exit(start_time, why)
end
end)
receive do
pid -> pid
end
end
def spawn_link(mod, func, args) do
root_pid = self()
spawn(fn ->
Process.flag(:trap_exit, true)
pid = :erlang.spawn_link(mod, func, args)
send(root_pid, pid)
start_time = :calendar.local_time
receive do
{:EXIT, ^pid, why} -> print_on_exit(start_time, why)
end
end)
receive do
pid -> pid
end
end
def spawn(mod, func, args, time) do
pid = :erlang.spawn(mod, func, args)
spawn(fn ->
receive do
after time ->
:io.format("About to kill process, but is it alive? ~p~n", [Process.alive?(pid)])
Process.exit(pid, :kill)
end
end)
pid
end
defp running_loop() do
receive do
after 5_000 -> IO.puts "I'm still running"
end
running_loop
end
def i_am_still_running(name) do
:erlang.spawn(&running_loop/0) |> Process.register(name)
end
defp running_loop_monitor(name) do
ref = Process.monitor(name)
receive do
{:DOWN, ^ref, :process, _, why} -> i_am_still_running(name)
end
running_loop_monitor(name)
end
def monitor_runner(name) do
:erlang.spawn(fn -> running_loop_monitor(name) end)
end
defp print_on_exit(start_time, why) do
end_time = :calendar.local_time
:io.format("Why ~p, worked ~p~n", [why, :calendar.time_difference(start_time, end_time) ])
end
def normal() do
receive do
after 3_000 -> IO.puts "exiting"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment