在OS X中以编程方式获取正在运行的应用程序包。

huangapple go评论89阅读模式
英文:

Programmatically get running application bundles in OS X

问题

我正在尝试获取所有正在运行的应用程序包的列表。用户启动的GUI应用程序,如Dock显示的应用程序或Activity Monitor(它在某些进程旁边显示一个图标)。我发现可以使用sysctl()KERN_PROC_ALL来获取所有正在运行的进程列表,但这不会告诉我它们来自哪个应用程序包。像Minecraft这样的应用程序只会显示为java,这并不是很有用。

我发现在活动监视器中的进程组名称大致显示了我想要知道的内容:
在OS X中以编程方式获取正在运行的应用程序包。
<sub>(来源:gdries.nl)</sub>

实现语言并不重要。目前正在使用C和Go进行开发,但如果需要其他环境,也没有问题。我只想检测用户正在运行哪些应用程序,以便记录每个应用程序的使用时间。(家长控制功能做了类似的事情,但将其记录在我无法解析的plist文件中)

英文:

I'm trying to get a list of all running Application Bundles. GUI applications that the user has started, like the Dock is showing, or Activity Monitor (it shows an icon next to certain processes). I found that I could use sysctl() with KERN_PROC_ALL to get a list of all running processes, but that won't tell me which application bundle they are from. Applications like Minecraft just show up as java and that's not very useful.

I did find that the process group name in activity monitor shows roughly what I want to know:
在OS X中以编程方式获取正在运行的应用程序包。
<sub>(source: gdries.nl)</sub>

The implementation language is not important. Currently working in C and go, but if some other environment turns out to be required that's not a problem. All I want to do is detect which applications the user has running so I can log the time that each has been used. (Parental Controls does something similar but logs it in plist files that I can't parse)

答案1

得分: 19

我找到了一种使用Swift和Cocoa API来实现的方法。理论上,使用纯C也应该是可能的,但对于我的应用程序来说,这已经足够好了。

import Foundation
import AppKit

// 获取所有正在运行的应用程序
let workspace = NSWorkspace.shared
let applications = workspace.runningApplications

for app in applications {
    print(app)
}

app 是一个 NSApplication 对象,它有一个捆绑标识符,这就是我想知道的内容。

英文:

I found a way to do it using Swift and Cocoa APIs. Presumably, this should also be possible using plain C, but this is good enough for my application.

import Foundation
import AppKit

// Get all running applications
let workspace = NSWorkspace.shared
let applications = workspace.runningApplications

for app in applications {
    print(app)
}

app is an NSApplication object, and that has a bundle identifier, which is what I wanted to know.

huangapple
  • 本文由 发表于 2015年1月15日 08:02:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/27954721.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定