微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ruby – 双叉和stdin

我编写了这段代码来在守护进程中运行我的进程.目标是即使我关闭其父进程也要使此进程运行.现在,我希望能够在其标准输入中写一些东西.我该怎么办 ?这是代码.

def daemonize(cmd, options = {})
  rd, wr = IO.pipe
  p1 = Process.fork {
    Process.setsid
    p2 = Process.fork {
      $0 =  cmd #Name of the command
      pidfile = File.new(options[:pid_file], 'w')
      pidfile.chmod( 0644 )
      pidfile.puts "#{Process.pid}"
      pidfile.close
      Dir.chdir(ENV["PWD"] = options[:working_dir].to_s) if options[:working_dir]
      File.umask 0000
      STDIN.reopen '/dev/null'
      STDOUT.reopen '/dev/null', 'a'
      STDERR.reopen STDOUT
      Signal.trap("USR1") do
        Console.show 'I just received a USR1', 'warning'
      end
      ::Kernel.exec(*Shellwords.shellwords(cmd)) #Executing the command in the parent process
      exit
    }
    raise 'Fork Failed!' if p2 == -1
    Process.detach(p2) # divorce p2 from parent process (p1)
    rd.close
    wr.write p2
    wr.close
    exit
  }
  raise 'Fork Failed!' if p1 == -1
  Process.detach(p1) # divorce p1 from parent process (shell)
  wr.close
  daemon_id = rd.read.to_i
  rd.close
  daemon_id
end

有没有办法在管道中重新打开stdin而不是/ dev / null,我可以在其中编写?

解决方法:

一个fifo怎么样?在linux中,您可以使用mkfifo命令:

$mkfifo /tmp/mypipe

然后你可以在那个管道上重新打开STDIN:

STDIN.reopen '/tmp/mypipe'
# Do read-y things

其他任何东西都可以写入该管道:

$echo "roflcopter" > /tmp/mypipe

允许ruby进程读取数据.

(更新)警告阻止

由于fifos阻塞直到读取和写入(例如读取被阻止,除非有写入,反之亦然),最好用多个线程处理.一个线程应该执行读取,将数据传递到队列,另一个线程应该处理该输入.以下是这种情况的一个例子:

require 'thread'

input = Queue.new
threads = []

# Read from the fifo and add to an input queue (glorified array)
threads << Thread.new(input) do |ip|
  STDIN.reopen 'mypipe'
  loop do
    if line = STDIN.gets
      puts "Read: #{line}"
      ip.push line
    end
  end
end

# Handle the input passed by the reader thread
threads << Thread.new(input) do |ip|
  loop do
    puts "Ouput: #{ip.pop}"
  end
end

threads.map(&:join)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐