Ruby进程(2) Process创建和回收 --- Process.fork, Process.wait和Process.detach
Process.fork{}
当block为空的时候,fork会返回2次结果,一次是在父进程中,返回子进程的pid,一次是在子进程中,返回nil。
Creates a subprocess. If a block is specified, that block is run in the subprocess, and the subprocess terminates with a status of zero.
Otherwise, the fork call returns twice, once in the parent, returning the process ID of the child, and once in the child, returning nil.
# Process.fork 会运行两次,第一次返回子进程pid,第二次返回nil
pid = Process.fork
puts "current pid :#{pid}"
if pid.nil? then
puts "# In child"
puts exec('ls ~')
else
puts "# In Parent"
puts "Sub Process ID:#{Process.wait(pid)}"
end
Source: http://stackoverflow.com/questions/806267/ruby-how-to-fire-and-forget-a-subprocess
Process.wait()
当进程退出时会保留一些关于退出状态的信息。这些状态信息并不能清除,直到它被父进程使用Process.wait来使用。
Process.wait(pid) Waits for a child process to exit, returns its process id, and sets $? to a Process::Statusobject containing information on that process.
Process.wait(-1) Waits for any child process (the default if no pid is given).
Process.detach()
Process.detach(pid) to register disinterest in their status; otherwise, the operating system may accumulate zombie processes.