Created
September 23, 2012 03:49
-
-
Save keating/3768787 to your computer and use it in GitHub Desktop.
使用fork启动一个进程
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| pid = fork { `nohup ruby GpsReader.rb 1 &` } | |
| # 这种写法能得到一个子进程的PID,但不是shell命令所运行进程的PID,若shell命令启动一个服务(一直运行),那么此子进程也不会死掉(与block是个while true,子进程便不会死掉一样) | |
| pid = fork { exec "`nohup ruby GpsReader.rb 1 &`" } | |
| # 这种写法能得到一个子进程的PID,同样不是shell命令进程的PID,子进程马上就结束了(ps S -C ruby或ps S -p your_PID),是exec方法在起作用(Replaces the current process by running the given external _command_),所以,在ruby代码运行一个shell命令时,使用exec要比直接`少一个进程 | |
| Process.detach(pid) | |
| puts pid | |
| while true | |
| puts "i am father..." | |
| sleep 2 | |
| end | |
| # 所以,fork + block这中写法,适合于运行一段真实的ruby代码,比如一个包含while true的方法,这样得到的子进程PID便是真是需要的,如 | |
| def xxx | |
| while true | |
| puts "i am running" | |
| sleep 2 | |
| end | |
| end | |
| pid = fork { xxx } | |
| Process.detach(pid) | |
| puts pid | |
| while true | |
| puts "i am father..." | |
| sleep 2 | |
| end | |
| # 无block的fork: 参考kernel.rb中fork()的说明 | |
| # 对于我的需求来讲,在fork块中运行一个ruby方法是最可取的,因为没有非得使用shell去运行的命令,所以可以轻易得到PID;如果需要运行shell命令,还需要得到PID,那么需要去做其它尝试了~ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment