`
秦朝古月
  • 浏览: 223815 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

读《The Ruby Way》之运行外部程序

    博客分类:
  • Ruby
阅读更多
西班牙输了,这次世界杯强队的表现真是没话可说了。

Ruby里调用外部程序的方法有三种,systemexec重音符(`)
先看一下system
# Linux
system("rm", "/tmp/file1")
system("rm /tmp/file2")
system("ls -l | hea -n l")

# Windows
system("notepad.exe", "myfile.txt")
system("cmd /c dir", "somefile")

system是无法捕获外部命令的输出的。
exec和system很像,但是exec后边的代码是不会被执行的。
重音符(`),是可以捕获外部命令输出的,也可以写成%x的形式。
listing = `ls -l`
now = `date`
listing = %x(ls -l)
now = %x(date)

可以使用fork方法创建新进程,wait和wait2方法用来等待子进程的返回,waitpid和waitpid2可以等待特定的子进程。Windows不支持fork。
pid1 = ford { sleep 5; exit 3 }
pid2 = ford { sleep 2; exit 3 }

Process.wait   # 返回 pid2
Process.wait2  # 返回 [pid1, 768],768是经过左偏移的退出状态

pid3 = ford { sleep 5; exit 3 }
pid4 = ford { sleep 2; exit 3 }

Process.waitpid(pid4, Process::WHOHANG)   # 返回 pid4
Process.waitpid2(pid3, Process::WHOHANG)  # 返回 [pid3, 768]

pid和ppid分别返回当前进程及其父进程的进程ID。可以用kill方法将UNIX式信号发送给进程。
Process.kill(1, pid1)        # 把信号1送给pid1
Process.kill("HUP", pid2)    # 把信号HUP送给pid2
Process.kill("SIGHUP", pid3) # 把信号SIGHUP送给pid3
Process.kill("SIGHUP", 0)    # 把信号SIGHUP送给自己
分享到:
评论
1 楼 finger 2014-07-18  
还有 Open3.capture 系列 和 Open3.popen 系列。
重音符无法取得错误信息,上面的命令可以同时取得标准输出,错误输出以及状态。

相关推荐

Global site tag (gtag.js) - Google Analytics