erlang 当父进程死亡时,进程send_link不工作,即使在取消链接之后也是如此

jtw3ybtb  于 2023-04-27  发布在  Erlang
关注(0)|答案(1)|浏览(184)

我有

Process.send_after(self(), {:do_thing, type, x, z, 0}, 60_000)

然后如果父进程死了,那就永远不会发生了

{:ok, pid} =
        Task.start_link(fn ->
          Process.send_after(self(), {:do_thing, type, x, z, 0}, 60_000)
        end)
      Process.unlink(pid)

但还是没解决我该怎么办
我也试过
this = self()然后是Process.send_after(this, {:do_thing, type, x, z, 0}, 60_000),但它不起作用。

yx2lnoni

yx2lnoni1#

如流程模块文档所述:
如果给定的dest是一个未激活的PID,或者当给定的PID退出时,计时器将自动取消。
如果dest进程在计时器关闭时仍处于活动状态,则可以使用一个示例。下面的示例显示了一个Dog进程生成一个Cat进程,然后Cat进程调用Process.send_after/3Process.send_after/3将消息发送回第三个进程。当计时器关闭时,Dog和Cat进程都不再存在。

defmodule Start do
  def spawn_dog do
    spawn(Dog, :bark, [ self() ])

    receive do
      msg -> IO.puts("Start process got message: #{msg}")
    end

  end
end

defmodule Dog do
  def bark(start_pid) do
    IO.puts("Dog process says bark.")
    spawn(Cat, :meow, [start_pid])

    IO.puts("Dog process exiting.")
  end

end

defmodule Cat do
  def meow(target_pid) do
    IO.puts("Cat process says meow.")
    Process.send_after(target_pid, "Cat wants food.", 3000) #Dog process above will exit
                                                            #before timer goes off.
    IO.puts("Cat process exiting.")  #Cat process will exit before timer goes off.
  end
end

在iex中:

iex(21)> c("start.ex")    
warning: redefining module Start (current version defined in memory)
  start.ex:1

warning: redefining module Dog (current version defined in memory)
  start.ex:12

warning: redefining module Cat (current version defined in memory)
  start.ex:22

[Cat, Dog, Start]

iex(22)> Start.spawn_dog()
Dog process says bark.
Dog process exiting.
Cat process says meow.
Cat process exiting.
Start process got message: Cat wants food.
:ok

相关问题