确定一个特定的过程

Identify a specific process

我正在考虑创建一个 gem 可以 return 我们目前 运行 的终端类型,无论是 Ubuntugnome terminalWindowCommand Processor。我们在这个问题中称这个为gem "Identifier"。

我希望能够做到这一点。

WindowCommand Procesor中:

> irb
require 'identifier'
Identifier.identify #=> 'Command Processor'

UbuntuGnome Terminal中:

$ irb
require 'identifier'
Identifier.identify #=> 'Gnome Terminal'

首先,我很想知道您是否有找到这些信息的巧妙方法。请记住,它必须适用于:

我想的方法很简单。首先,我使用纯 ruby 的片段确定 os: RbConfig::CONFIG['host_os'] 然后,我使用 sys-proctable gem 获取所有 运行 进程的数组。然后我简单地检查这个进程数组是否包含可用于检测到的 OS 的终端程序。这并不聪明,我只需要对 Windows、Linux、FreeBSD、Solaris、HP-UX、OS X、AIX 的每个可用终端进行硬编码,但仍然可行.这是一个有限的列表。而如果不能定义某人的终端,那也没关系。它会引发一个错误,清楚地解释问题,并向 gem 的 github 项目目录添加一个 link,他们可以在其中将他们的终端名称及其进程名称添加到项目中。无论如何,我的想法看起来像这样(伪代码):

proc_table = Sys::ProcTable.ps
case RbConfig::CONFIG['host_os']
when "i686-linux"
    utilized = proc_table & ['terminator','tilda','guake','gnome-terminal','Yakuake','ROXTerm']
when "x64-mingw32"
    utilized = proc_table & ['windows-command-host']
when "some-other-madness"
...
end

现在,这实际上应该适用于 most 个案例,但有一个边缘案例让我很烦恼! 如果他们同时有两个终端程序运行怎么办?例如,如果安装了 gnome-terminal 和 ROXTerm 并且 运行?

会怎么样

我们的 utilized 变量看起来像这样:['gnome-terminal','ROXTerm']我们如何选择哪一个?问题来了……你有没有巧妙的方法我们可以以某种方式以某种方式操纵进程来识别哪个进程是当前的终端运行 脚本?或者其他的东西?如果这个问题没有得到任何答案,我只会告诉用户简单地退出他们不使用的终端,但我希望它能够自动工作,我觉得它是如此 possible。脚本已经从终端A执行,终端A和终端B都是运行...so choose终端A!看起来并不疯狂。

有什么想法吗?请记住,我们正在识别 OS,因此 OS 特定的黑客攻击是可以接受的。

Related

构建进程树的分支来确定终端怎么样?

require 'sys/proctable'

def process_tree_branch pid = Process.pid
  proc_table = Sys::ProcTable.ps
  by_pid = proc_table.inject({}) do |r, p| r[p.pid] = p; r; end

  result = []

  current = by_pid[pid]
  while current && current.pid != 0 do
    result << current
    current = by_pid[current.ppid]
  end

  result
end

puts process_tree_branch.map(&:cmdline).inspect

# ["ruby example.rb", "-bash", "sshd: vb@pts/0", "sshd: vb [priv]", "/usr/sbin/sshd -D", "/sbin/init"]