开发者

osx - How to get a process id (PID) programmatically?

How can I get a process' ID? I require the ID in order to kill that process. I know the name of the process.

Th开发者_Go百科anks!


The best approach is to use -[NSWorkspace launchedApplications] for 10.5- and -[NSWorkspace runningApplicattions] for 10.6+ apps. One returns a dictionary with specified keys, including process ID and bundle name and location info (when available), the other an NSRunningApplication object.


let pid: Int32 = ProcessInfo.processInfo.processIdentifier
print("pid: \(pid)")


First of all, process name is not uniquely identify the process. There could be many processes with the same name, or processes can even change their name as you see them (i.e. PostgreSQL server is forking and changing argv[0] so you can see who is master, who is working process etc). But anyway, you will need an API to list processes and get their details - procps will do it for you.

UPDATE: Oh, I didn't notice OSX the first time. For OS X, you have to use NetBSD API (don't ask). Please see KVM (Kernel Data Access Library) documentation. The API is different, the idea is still the same.


Use NSRunningApplication

NSArray *runningApplications = [NSRunningApplication runningApplicationsWithBundleIdentifier:@"com.bundleIdentifier"];
if (runningApplications.count == 1) {
    NSRunningApplication *app = runningApplications[0];
    pid = [app processIdentifier];
}

Note: -[NSWorkspace launchedApplications] is deprecated for 10.6 and above.


A quick hack: Spawn a shell call to killall, which kills a process by name.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜