本文介绍了如何触发并忘记子流程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个运行时间很长的进程,我需要它来启动另一个进程(该进程也将运行很长时间).我只需要启动它,然后完全忘记它.

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.

我设法从Ruby编程手册中摘取了一些代码,从而完成了所需的工作,但是我想找到最佳/正确的方法,并了解发生了什么.这是我最初得到的:

I managed to do what I needed by scooping some code from the Programming Ruby book, but I'd like to find the best/right way, and understand what is going on. Here's what I got initially:

exec("whatever --take-very-long") if fork.nil?
Process.detach($$)


在检查了以下答案之后,我最终得到了这段代码,这似乎更有意义:

(pid = fork) ? Process.detach(pid) : exec("foo")


我希望对fork的工作方式进行一些解释. [已经知道了]

I'd appreciate some explanation on how fork works. [got that already]

分离$$是吗?我不知道为什么会这样,我真的很想更好地了解这种情况.

Was detaching $$ right? I don't know why this works, and I'd really love to have a better grasp of the situation.

推荐答案

fork函数将您的进程分为两部分.

The fork function separates your process in two.

两个进程都将接收该函数的结果.子项的值为零/nil(因此知道它是子项),而父项则接收子项的PID.

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.

因此:

exec("something") if fork.nil?

将使子进程开始执行某事",而父进程将继续执行该操作.

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

请注意,exec() 将""替换为当前进程,因此子进程将永远不会执行任何后续的Ruby代码.

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

Process.detach()的调用似乎不正确.我本来希望其中包含孩子的PID,但是如果我正确阅读了您的代码,它实际上是在分离父进程.

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.

这篇关于如何触发并忘记子流程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-30 01:54