【问题标题】:Read I/O (in this case the Serial Port) without blocking (Ruby)无阻塞读取 I/O(在本例中为串行端口)(Ruby)
【发布时间】:2012-11-28 10:51:51
【问题描述】:

我正在尝试使用串行端口 gem 读取 Ruby 中的串行端口。问题是有时没有要读取的数据,当我告诉程序读取串口时,程序挂起......我试过使用sp.readsp.readlinesp.readlines;它们都会导致程序阻塞(在 Windows 下)。

有人知道是否有不会导致阻塞的方法吗?基本上,我希望如果没有要读取的数据,

读取结果为零。

谢谢。

【问题讨论】:

    标签: ruby io


    【解决方案1】:

    你可以使用IO#read_nonblock:

    begin
      result = io.read_nonblock(maxlen)
    rescue IO::WaitReadable # this is raised when there's no data in the stream
      # don't wait and return nil
      result = nil
    end
    

    【讨论】:

    • 谢谢。我会调查的。我以为我试过了,但没用,但细微差别犯了一个错误。从内存中,readline 在 Linux 中没有阻塞,但在 Windeos 中阻塞,这没有任何意义:(
    • 实际上,您上面的答案对我来说实际上并不适用,但如果我删除 IO::WaitReadable 并离开救援以捕获所有异常,它确实有效。
    • 捕捉IO::EAGAINWaitReadable 应该可以工作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-14
    • 1970-01-01
    • 2020-05-24
    • 1970-01-01
    • 1970-01-01
    • 2011-08-02
    相关资源
    最近更新 更多