gpt4 book ai didi

ruby - 在不同的进程中生成命令提示符并在 Windows 上发送/接收命令

转载 作者:数据小太阳 更新时间:2023-10-29 08:01:10 25 4
gpt4 key购买 nike

我手头有一个问题,它要求我生成一个命令提示符作为一个不同的进程并向它发送一些命令并捕获/解析命令输出。这种交互需要采用父子进程的形式,其中所有命令都可以放在一个 ruby​​ 文件中,并且在运行 ruby​​ 文件时,命令被发送到控制台(命令提示符)并从中接收输出并在 ruby​​ 脚本中处理。

我要遵循的一般逻辑是:

  1. 使用 fork 生成不同的进程并获取进程 ID
  2. 获取流程的流
  3. 写入进程的输入流并从输出流读取。

我使用的环境是安装了 Ruby 1.9.2 的 Windows XP 机器。我下载了在 here 上找到的 win32 进程库.通过使用该库,我可以按如下方式执行第 1 步

require 'win32/process'
APP_NAME = "C:\\Windows\\system32\\cmd.exe"
process_info = Process.create(:app_name => APP_NAME,
:creation_flags => Windows::Process::CREATE_NEW_CONSOLE,
:process_inherit => false,
:thread_inherit => true,
:cwd => "C:\\"
)

由于 win32-process 库是基于在 Windows 上使用进程和线程的,所以我尝试浏览 MSDN帮助它。在阅读 Creation of a Console 时在文章中,我发现 GetStdHandle 方法可用于获取输入和输出流的句柄。但是,我在 win32-process 的任何地方都找不到这个方法。

有人可以指导我如何进行第 2 步和第 3 步吗?

请问还有其他方法可以解决手头的问题吗?

此外,我想了解更多关于进程间通信或一般的进程生成和 fork 的信息,所以有人可以告诉我一些我可以研究它们的好的引用资料吗?

提前致谢

最佳答案

这里是一个在 windows 中使用 IO.popen 的例子,如果它与 stdlib 一起工作,就不要使用 gems

IO.popen("other_program", "w+") do |pipe|
pipe.puts "here, have some input"
pipe.close_write # If other_program process doesn't flush its output, you probably need to use this to send an end-of-file, which tells other_program to give us its output. If you don't do this, the program may hang/block, because other_program is waiting for more input.
output = pipe.read
end

# You can also use the return value from your block. (exit code stored in $? as usual)
output = IO.popen("other_program", "w+") do |pipe|
pipe.puts "here, have some input"
pipe.close_write
pipe.read
end

关于ruby - 在不同的进程中生成命令提示符并在 Windows 上发送/接收命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10901997/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com