Osx - How to get the process identifier (PID) programmatically?

How can I get the process id? I need an identifier to kill this process. I know the name of the process.

Thanks!

+4
source share
5 answers

The best approach is to use - [NSWorkspace running applications] for 10.5+ and [NSWorkspace runningApplicattions] for 10.6+ applications. One returns a dictionary with the specified keys, including the process identifier and package name and location information (if available), and the other an NSRunningApplication object.

+3
source

First of all, the process name does not uniquely identify the process. There could be many processes with the same name, or processes may even change their name as you see them (ie, the PostgreSQL Server expands and changes argv [0] so you can see who is the master, who is the worker process, etc.). But in any case, you will need an API to list the processes and get their details - procps will do this for you.

UPDATE: Oh, I did not notice OSX for the first time. For OS X, you should use the NetBSD API (don't ask). See the KVM (kernel data library) documentation . The API is different, the idea is the same.

+2
source

Quick hack: Call the killall shell call, which kills the process by name.

+1
source

Use NSRunningApplication

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

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

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