2

我正在尝试运行 shell 脚本并捕获 PID、STDERR、STDOUT 和 shell 的退出状态。

我使用的是 Ruby 1.8.7,所以 Open3 没有办法获取 PID。我尝试使用 open4 gem,但不幸的是在写入过程中挂起了一些脚本,手动运行时运行良好。

我想找到一个替代方案。您的指导将不胜感激!

4

1 回答 1

0

不幸的是,没有一种简单的方法可以做到这一点。我试过 PTY.spawn 但有时它会执行失败。如果你不能使用 open3,那么你可以使用 FIFO,但它会有点乱。这是我在 1.8.7 上使用的解决方案:

# Avoid each thread having copies of all the other FDs on the fork
def closeOtherFDs
  ObjectSpace.each_object(IO) do |io|
    unless [STDIN, STDOUT, STDERR].include?(io)
      unless(io.closed?)
        begin
          io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
        rescue ::Exception => err
        end
      end
    end
  end
end


# Utilities for fifo method
require 'tempfile'
def tmpfifo
  # Use tempfile just to manage naming and cleanup of the file
  fifo = Tempfile.new('fifo.').path
  File.delete(fifo)
  system("/usr/bin/mkfifo",fifo)
  #puts "GOT: #{fifo} -> #{$?}"
  fifo
end

# fifo homebrew method
def spawnCommand *command
  ipath = tmpfifo
  opath = tmpfifo
  #epath = tmpfifo

  pid = fork do
    #$stdin.reopen(IO.open(IO::sysopen(ipath,Fcntl::O_RDONLY)))
    $stdin.reopen(File.open(ipath,'r'))
    $stdout.reopen(File.open(opath,'w'))
    #$stderr.reopen(File.open(epath,'w'))
    $stderr.close
    closeOtherFDs
    exec(*command)
    exit
  end

  i = open ipath, 'w'
  #i.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) # Doesn't work?  Use closeOtherFDs
  o = open opath, 'r'
  #e = open epath, 'r'
  e = nil
  [o,i,e].each { |p| p.sync = true if p }

  [o,i,e]
end

不,它不干净。但是因为它使用fork并且自己处理三个句柄,所以你可以得到PID并完成open3所做的事情。

确保在之后关闭文件句柄!之后清理的收益版本可能更有意义。

于 2013-10-16T10:35:38.390 回答