swiftprocesskill-process

Killing a process with swift programmatically


I am trying to find a way to identify and kill specific processes in a Mac Application. Is there a built-in class that has functions that can return the list of running processes? There is one way of running terminal commands using Process() and execute the /usr/bin/killall command to kill processes but I need to do it programmatically as running terminal commands using an application is not a good practice. For example, deleting a file can also be done by running a terminal command using Process() while the better way to do it is using FileManager.default.remomveItem().


Solution

  • If you're looking for an application (rather than a process), then see NSWorkspace.shared.runningApplications. You can call terminate() or forceTerminate() on those elements.

    If you want a list of all BSD processes (what you would get from a call to ps for example), that's done with sysctl (the code in the Q&A is in C; you'd have to wrap it to Swift, or rewrite it). I don't believe there's any Cocoa wrapper for that. To kill a process, once you have its PID, use signal, which is what the kill Unix command uses. Typically you want to send SIGTERM, which is a normal shutdown. To force-kill a process, send SIGKILL.