【发布时间】:2011-05-11 05:28:21
【问题描述】:
我有一组需要从 Ruby 脚本运行的任务,但是一个特定的任务总是在退出前等待 STDIN 上的 EOF。
显然这会导致脚本在等待子进程结束时挂起。
我有子进程的进程 ID,但没有管道或任何类型的句柄。如何打开一个进程的 STDIN 句柄来发送 EOF 给它?
【问题讨论】:
标签: ruby unix process ipc stdin
我有一组需要从 Ruby 脚本运行的任务,但是一个特定的任务总是在退出前等待 STDIN 上的 EOF。
显然这会导致脚本在等待子进程结束时挂起。
我有子进程的进程 ID,但没有管道或任何类型的句柄。如何打开一个进程的 STDIN 句柄来发送 EOF 给它?
【问题讨论】:
标签: ruby unix process ipc stdin
编辑:鉴于您没有启动脚本,我想到的一个解决方案是在使用您的 gem 时将 $stdin 置于您的控制之下。我建议类似:
old_stdin = $stdin.dup
# note that old_stdin.fileno is non-0.
# create a file handle you can use to signal EOF
new_stdin = File::open('/dev/null', 'r')
# and make $stdin use it, instead.
$stdin.reopen(new_stdin)
new_stdin.close
# note that $stdin.fileno is still 0, though now it's using /dev/null for input.
# replace with the call that runs the external program
system('/bin/cat')
# "cat" will now exit. restore the old state.
$stdin.reopen(old_stdin)
old_stdin.close
如果您的 ruby 脚本正在创建任务,它可以使用IO::popen。例如,cat,在不带参数运行时,将在标准输入上等待 EOF 退出,但您可以运行以下命令:
f = IO::popen('cat', 'w')
f.puts('hello')
# signals EOF to "cat"
f.close
【讨论】: