6

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!

Alex
  • 7,432
  • 20
  • 75
  • 118

5 Answers5

5
let pid: Int32 = ProcessInfo.processInfo.processIdentifier
print("pid: \(pid)")
neoneye
  • 50,398
  • 25
  • 166
  • 151
5

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.

nomothetis
  • 233
  • 2
  • 7
  • 1
    And why is it better? At the end of the day it will still go to that C-level API. So if you already have a C program, why bother with Objective-C? –  Jun 02 '11 at 15:38
  • It's only better if you're in an Objective-C app; it's a reasonable assumption when people look for programmatic help on OS X. In plain C, a plain C library is obviously better.Sorry it took so long—I didn't get an email about the comment. – nomothetis Sep 13 '11 at 14:44
2

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.

zaph
  • 111,848
  • 21
  • 189
  • 228
  • from Apple: NSRunningApplication is a class to manipulate and provide information for a single instance of an application. **Only user applications are tracked; this does not provide information about every process on the system.** – Jeff Brown Oct 03 '16 at 13:24
2

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.

Community
  • 1
  • 1
1

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

Jens
  • 6,173
  • 2
  • 24
  • 43