欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

读《The Ruby Way》之运行外部程序 博客分类: Ruby RubyLinuxWindowsUnixC 

程序员文章站 2024-03-16 09:53:28
...
西班牙输了,这次世界杯强队的表现真是没话可说了。

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送给自己