當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Ruby PTY模塊用法及代碼示例

本文簡要介紹ruby語言中 PTY模塊 的用法。

創建和管理偽終端 (PTY)。另見en.wikipedia.org/wiki/Pseudo_terminal

PTY 允許您使用 ::open ::spawn 分配具有特定命令的新終端。

示例

在此示例中,我們將更改 factor 命令中的緩衝類型,假設 factor 使用 stdio 進行 stdout 緩衝。

如果使用 IO.pipe 而不是 PTY.open ,則此代碼將死鎖,因為因子的標準輸出已完全緩衝。

# start by requiring the standard library PTY
require 'pty'

master, slave = PTY.open
read, write = IO.pipe
pid = spawn("factor", :in=>read, :out=>slave)
read.close     # we dont need the read
slave.close    # or the slave

# pipe "42" to the factor command
write.puts "42"
# output the response from factor
p master.gets #=> "42: 2 3 7\n"

# pipe "144" to factor and print out the response
write.puts "144"
p master.gets #=> "144: 2 2 2 2 3 3\n"
write.close # close the pipe

# The result of read operation when pty slave is closed is platform
# dependent.
ret = begin
        master.gets     # FreeBSD returns nil.
      rescue Errno::EIO # GNU/Linux raises EIO.
        nil
      end
p ret #=> nil

相關用法


注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 PTY模塊。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。