如何在 Ruby 中打开进程的 STDIN?

发布于 2024-10-03 14:18:15 字数 151 浏览 3 评论 0原文

我有一组需要从 Ruby 脚本运行的任务,但是一个特定的任务在退出之前总是等待 STDIN 上的 EOF。

显然,这会导致脚本在等待子进程结束时挂起。

我有子进程的进程 ID,但没有管道或任何类型的句柄。如何打开进程 STDIN 的句柄以向其发送 EOF?

I have a set of tasks that I need to run from a Ruby script, however one particular task always waits for EOF on STDIN before quitting.

Obviously this causes the script to hang while waiting for the child process to end.

I have the process ID of the child process, but not a pipe or any kind of handle to it. How could I open a handle to the STDIN of a process to send EOF to it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

∞梦里开花 2024-10-10 14:18:15

编辑:鉴于您没有启动脚本,我想到的一个解决方案是在使用 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,当不带参数运行时,将在退出之前等待 stdin 上的 EOF,但您可以运行以下命令:

f = IO::popen('cat', 'w')
f.puts('hello')
# signals EOF to "cat"
f.close

EDIT: Given that you aren't starting the script, a solution that occurs to me is to put $stdin under your control while using your gem. I suggest something like:

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


If your ruby script is creating the tasks, it can use IO::popen. For example, cat, when run with no arguments, will wait for EOF on stdin before it exits, but you can run the following:

f = IO::popen('cat', 'w')
f.puts('hello')
# signals EOF to "cat"
f.close

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文