Reputation: 7612
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!
Upvotes: 7
Views: 7856
Reputation: 52201
let pid: Int32 = ProcessInfo.processInfo.processIdentifier
print("pid: \(pid)")
Upvotes: 5
Reputation: 112857
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.
Upvotes: 2
Reputation: 233
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.
Upvotes: 5
Reputation:
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.
Upvotes: 2
Reputation: 6329
A quick hack: Spawn a shell call to killall, which kills a process by name.
Upvotes: 1