ruby - 如何阻止读取 Ruby 中的命名管道?

标签 ruby named-pipes blocking

我正在尝试设置一个 Ruby 脚本,该脚本在循环中从命名管道读取数据,阻塞直到管道中的输入可用。

我有一个定期将调试事件放入命名管道的进程:

# Open the logging pipe
log = File.open("log_pipe", "w+") #'log_pipe' created in shell using mkfifo
...
# An interesting event happens
log.puts "Interesting event #4291 occurred"
log.flush
...

然后我想要一个单独的进程,它将从此管道中读取并在事件发生时将事件打印到控制台。我试过使用这样的代码:

input = File.open("log_pipe", "r+") 
while true
  puts input.gets  #I expect this to block and wait for input
end
# Kill loop with ctrl+c when done

我希望 input.gets 阻塞,耐心等待直到新输入到达 fifo;但它立即读取 nil 并再次循环,滚动到控制台窗口的顶部。

我试过的两件事:

  1. 我已经用“r”和“r+”打开了输入 fifo——无论哪种方式我都遇到了同样的问题;

  2. 我已尝试确定我的写入过程是否正在发送 EOF(我听说这会导致读取 fifo 关闭)-- 据我所知,事实并非如此。

一些背景:

如果有帮助,这是我正在尝试做的事情的“大局” View :

我正在开发一款在 RGSS 中运行的游戏,RGSS 是一种基于 Ruby 的游戏引擎。由于它没有很好的集成调试,我想在游戏运行时设置一个实时日志——当游戏中发生事件时,我希望消息显示在侧面的控制台窗口中。我可以使用类似于上面编写器代码的代码将 Ruby 游戏代码中的事件发送到命名管道;我现在正在尝试设置一个单独的进程,该进程将等待事件出现在管道中并在它们到达时显示在控制台上。我什至不确定我是否需要 Ruby 来执行此操作,但这是我能想到的第一个解决方案。

请注意,我正在使用来自 cygwin 的 mkfifo,我碰巧安装了它;我想知道这是否是我麻烦的根源。

如果它对任何人有帮助,这正是我在 irb 中看到的“读者”流程:

irb(main):001:0> input = File.open("mypipe", "r")
=> #<File:mypipe>
irb(main):002:0> x = input.gets
=> nil
irb(main):003:0> x = input.gets
=> nil

我不希望 002 和 003 处的 input.gets 立即返回——我希望它们会阻塞。

最佳答案

我找到了一个解决方案,可以完全避免使用 Cygwin 不可靠的命名管道实现。 Windows 有自己的命名管道工具,甚至还有一个名为 win32-pipe 的 Ruby Gem。使用它。

不幸的是,似乎无法在 RGSS 脚本中使用 Ruby Gems;但是通过剖析 win32-pipe gem,我能够将相同的想法整合到 RGSS 游戏中。此代码是将游戏事件实时记录到后台 channel 所需的最低限度,但它对于深度调试非常有用。

我在'Main'之前添加了一个新的脚本页面并添加了这个:

module PipeLogger
  # -- Change THIS to change the name of the pipe!
  PIPE_NAME = "RGSSPipe"

  # Constant Defines
  PIPE_DEFAULT_MODE        = 0            # Pipe operation mode
  PIPE_ACCESS_DUPLEX       = 0x00000003   # Pipe open mode
  PIPE_UNLIMITED_INSTANCES = 255          # Number of concurrent instances
  PIPE_BUFFER_SIZE         = 1024         # Size of I/O buffer (1K)
  PIPE_TIMEOUT             = 5000         # Wait time for buffer (5 secs)
  INVALID_HANDLE_VALUE     = 0xFFFFFFFF   # Retval for bad pipe handle

  #-----------------------------------------------------------------------
  # make_APIs
  #-----------------------------------------------------------------------
  def self.make_APIs
    $CreateNamedPipe     = Win32API.new('kernel32', 'CreateNamedPipe', 'PLLLLLLL', 'L')
    $FlushFileBuffers    = Win32API.new('kernel32', 'FlushFileBuffers', 'L', 'B')
    $DisconnectNamedPipe = Win32API.new('kernel32', 'DisconnectNamedPipe', 'L', 'B')
    $WriteFile           = Win32API.new('kernel32', 'WriteFile', 'LPLPP', 'B')
    $CloseHandle         = Win32API.new('kernel32', 'CloseHandle', 'L', 'B')
  end

  #-----------------------------------------------------------------------
  # setup_pipe
  #-----------------------------------------------------------------------
  def self.setup_pipe
    make_APIs
    @@name = "\\\\.\\pipe\\" + PIPE_NAME

    @@pipe_mode = PIPE_DEFAULT_MODE
    @@open_mode = PIPE_ACCESS_DUPLEX
    @@pipe         = nil
    @@buffer       = 0.chr * PIPE_BUFFER_SIZE
    @@size         = 0
    @@bytes        = [0].pack('L')

    @@pipe = $CreateNamedPipe.call(
      @@name,
      @@open_mode,
      @@pipe_mode,
      PIPE_UNLIMITED_INSTANCES,
      PIPE_BUFFER_SIZE,
      PIPE_BUFFER_SIZE,
      PIPE_TIMEOUT,
      0
    )

    if @@pipe == INVALID_HANDLE_VALUE
      # If we could not open the pipe, notify the user
      # and proceed quietly
      print "WARNING -- Unable to create named pipe: " + PIPE_NAME
      @@pipe = nil
    else
      # Prompt the user to open the pipe
      print "Please launch the RGSSMonitor.rb script"
    end
  end

  #-----------------------------------------------------------------------
  # write_to_pipe ('msg' must be a string)
  #-----------------------------------------------------------------------
  def self.write_to_pipe(msg)
    if @@pipe
      # Format data
      @@buffer = msg
      @@size   = msg.size

      $WriteFile.call(@@pipe, @@buffer, @@buffer.size, @@bytes, 0)
    end
  end

  #------------------------------------------------------------------------
  # close_pipe
  #------------------------------------------------------------------------
  def self.close_pipe
    if @@pipe
      # Send kill message to RGSSMonitor
      @@buffer = "!!GAMEOVER!!"
      @@size   = @@buffer.size
      $WriteFile.call(@@pipe, @@buffer, @@buffer.size, @@bytes, 0)

      # Close down the pipe
      $FlushFileBuffers.call(@@pipe)
      $DisconnectNamedPipe.call(@@pipe)
      $CloseHandle.call(@@pipe)
      @@pipe = nil
    end
  end
end

要使用它,您只需要确保在编写事件之前调用PipeLogger::setup_pipe;并在游戏退出前调用 PipeLogger::close_pipe。 (我将设置调用放在“Main”的开头,并添加一个 ensure 子句来调用 close_pipe。)之后,您可以添加对 的调用PipeLogger::write_to_pipe("msg") 在任何脚本中的任何位置使用“msg”的任何字符串写入管道。

我已经用 RPG Maker XP 测试了这段代码;它也应该适用于 RPG Maker VX 及更高版本。

您还需要从管道中读取一些内容。有许多方法可以做到这一点,但一个简单的方法是使用标准的 Ruby 安装、win32-pipe Ruby Gem 和这个脚本:

require 'rubygems'
require 'win32/pipe'
include Win32

# -- Change THIS to change the name of the pipe!
PIPE_NAME = "RGSSPipe"

Thread.new { loop { sleep 0.01 } } # Allow Ctrl+C

pipe = Pipe::Client.new(PIPE_NAME)
continue = true

while continue
  msg = pipe.read.to_s
  puts msg

  continue = false if msg.chomp == "!!GAMEOVER!!"
end

我使用 Ruby 1.8.7 for Windowswin32-pipe gem上面提到的(请参阅 here 以获得有关安装 gems 的良好引用)。将以上内容保存为“RGSSMonitor.rb”并从命令行调用它作为 ruby RGSSMonitor.rb

注意事项:

  1. 上面列出的 RGSS 代码很脆弱;特别是,它不处理打开命名管道的失败。这在您自己的开发机器上通常不是问题,但我不建议发布此代码。
  2. 我还没有测试过它,但我怀疑如果你在没有运行进程来读取管道的情况下向日志写入很多东西(例如 RGSSMonitor.rb),你会遇到问题。 Windows 命名管 Prop 有固定大小(我在这里将其设置为 1K),默认情况下,写入将在管道被填满后阻塞(因为没有进程通过从中读取来“缓解压力”)。不幸的是,RPGXP 引擎会终止已停止运行 10 秒的 Ruby 脚本。 (我听说 RPGVX 取消了这个看门狗功能——在这种情况下,游戏将挂起而不是突然终止。)

关于ruby - 如何阻止读取 Ruby 中的命名管道?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9796258/

相关文章:

.net-2.0 - 当消息变大时,IpcChannel Remoting变慢

.net - 如何在没有 try-catch 的情况下检测 WCF 连接?

c - 从c中连接的udp套接字中读取返回

ruby-on-rails - 换行符搞砸了 <pre> 标签(Ruby on Rails)

java - Java 可以充当命名管道服务器吗?

ruby - 顶级程序从 ruby​​ 返回的值少于 linux 上的 bash

php - 如何在并发请求上创建php阻塞机制?

spring - 把阻塞代码包装成一个Mono flatMap,这还是非阻塞操作吗?

javascript - Rails 递归地包含 javascripts Assets 文件夹

ruby - 如何从命令行在 ruby​​ 中打开 STDOUT.sync