使用 Ruby 执行任意系统调用

Using Ruby to execute arbitrary system calls

这个问题是进入devops部门实习:

"Write a ruby library that executes arbitrary system calls (eg: “dmesg", "ping -c 1 www.google.com”) and provides separated output streams of stderr and stdout as well are providing the final return code of the process. Show your work with unit tests.”

我是否应该使用已经建立的系统调用并在 Ruby 代码中复制它们?这对我来说似乎很愚蠢。我是否应该想出自己的任意调用并编写一个包含错误和状态调用的库?

我不是在找人帮我写这篇文章。我觉得解决这个问题的第一步是理解它。

幸运的是,Ruby 使得与底层操作系统的交互变得非常容易。

您可以先阅读这些方法的文档:

此外,还有来自 stdlib 的 Open3 模块。

源头澄清

作业措辞不当,并且误用了一些术语。此外,我们只能猜测他们真正期望的是什么;适当的做法是直接要求公司澄清。

重新实现 Open3

话虽如此,他们可能想要的是一种将任何给定命令及其参数作为装饰方法处理的方法,类似于 Open3#capture3 来自标准库作品。这意味着您编写的代码应该将命令和任何参数作为参数。

例如,使用标准库中的Open3#capture3

require 'open3'

def command_wrapper cmd, *args
  stdout_str, stderr_str, status = Open3.capture3 "#{cmd} #{args.join ' '}"
end

command_wrapper "/bin/echo", "-n", "foo", "bar", "baz"
#=> ["foo bar baz", "", #<Process::Status: pid 31661 exit 0>]

我真诚地怀疑重新实现这个库有用,但这看起来确实是他们要求您做的。耸耸肩。

您还应该为重新实现编写单元测试,因此您将不得不使用内置框架(如 Test::Unit 或 MiniTest)或外部测试框架(如 RSpec,还是错误的。有关可用单元测试框架的更全面列表,请参阅 Ruby Toolbox