Ruby 调用本地程序

来源:互联网 发布:强制视频软件 编辑:程序博客网 时间:2024/06/14 05:08
碰到需要调用操作系统shell命令的时候,Ruby为我们提供了六种完成任务的方法:
1.Exec方法:
    Kernel#exec方法通过调用指定的命令取代当前进程:
  例子:
      $ irb
      >> exec 'echo "hello $HOSTNAME"'
         hello nate.local
      $
值得注意的是,exec方法用echo命令来取代了irb进程从而退出了irb。主要的缺点是,你无法从你的ruby脚本里知道这个命令是成功还是失败。
 
2.System方法。
  Kernel#system方法操作命令同上, 但是它是运行一个子shell来避免覆盖当前进程。如果命令执行成功则返回true,否则返回false。
 
 $ irb             
  >> system 'echo "hello $HOSTNAME"'
  hello nate.local
  => true
  >> system 'false' 
  => false
  >> puts $?
  256
  => nil
  >> 
3.反引号(Backticks,Esc键下面那个键)
$ irb
  >> today = `date`
  => "Mon Mar 12 18:15:35 PDT 2007n" 
  >> $?
  => #<Process::Status: pid=25827,exited(0)>
  >> $?.to_i
  => 0
这种方法是最普遍的用法了。它也是运行在一个子shell中。
4.IO#popen
  $ irb
  >> IO.popen("date") { |f| puts f.gets }
  Mon Mar 12 18:58:56 PDT 2007
  => nil
5.open3#popen3
$ irb
  >> stdin, stdout, stderr = Open3.popen3('dc') 
  => [#<IO:0x6e5474>, #<IO:0x6e5438>, #<IO:0x6e53d4>]
  >> stdin.puts(5)
  => nil
  >> stdin.puts(10)
  => nil
  >> stdin.puts("+")
  => nil
  >> stdin.puts("p")
  => nil
  >> stdout.gets
  => "15n"
6.Open4#popen4
$ irb
  >> require "open4" 
  => true
  >> pid, stdin, stdout, stderr = Open4::popen4 "false" 
  => [26327, #<IO:0x6dff24>, #<IO:0x6dfee8>, #<IO:0x6dfe84>]
  >> $?
  => nil
  >> pid
  => 26327
  >> ignored, status = Process::waitpid2 pid
  => [26327, #<Process::Status: pid=26327,exited(1)>]
  >> status.to_i
  => 256

转自:http://blackanger.blog.51cto.com/140924/43730

ruby获取pid文件中的pid进程是否运行

ruby获取pid文件中的pid进程是否运行,Linux/UNIX系统中,通常用pid文件来记录pid,ruby判断进程是否运行,在不知道pid的情况下,需要获取pid文件中的内容,并转换为整数值,然后采用kill,发送一个信号值,如果成功返回1,否则返回0,如果该进程没有权限操作,则会抛出一个异常Errno::EPERM,并且不能断定是否在运行。所以最好的办法是采用Process.getpgid 方法,如果该方法执行成功,则进程在运行,否则会抛出Errno::ESRCH异常。

 

def running?(pidfile)  begin    pid = IO.read(pidfile).to_i    pid >0&&Process.getpgid( pid )&&true  rescue    false  endend

 

如果pid文件不存在,会抛出异常,如果pid存在,但进程不存在,则Process.getpgid也会抛出异常。非常简洁的代码。

调用方法:

 

s = running?'/var/run/nginx.pid' puts s

转自:http://write.blog.csdn.net/postedit/8542995
原创粉丝点击