How can I get a process' ID? I require the ID in order to kill that process. I know the name of the process.
Thanks!
How can I get a process' ID? I require the ID in order to kill that process. I know the name of the process.
Thanks!
let pid: Int32 = ProcessInfo.processInfo.processIdentifier
print("pid: \(pid)")
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.
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.
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.