How to fire and forget a subprocess?

前端 未结 5 1289
深忆病人
深忆病人 2021-01-31 04:28

I have a long running process and I need it to launch another process (that will run for a good while too). I need to only start it, and then completely forget about it.

5条回答
  •  走了就别回头了
    2021-01-31 05:34

    The fork function separates your process in two.

    Both processes then receive the result of the function. The child receives a value of zero/nil (and hence knows that it's the child) and the parent receives the PID of the child.

    Hence:

    exec("something") if fork.nil?
    

    will make the child process start "something", and the parent process will carry on with where it was.

    Note that exec() replaces the current process with "something", so the child process will never execute any subsequent Ruby code.

    The call to Process.detach() looks like it might be incorrect. I would have expected it to have the child's PID in it, but if I read your code right it's actually detaching the parent process.

提交回复
热议问题