简体   繁体   English

以编程方式使用 swift 杀死进程

[英]Killing a process with swift programmatically

I am trying to find a way to identify and kill specific processes in a Mac Application.我正在尝试找到一种方法来识别和终止 Mac 应用程序中的特定进程。 Is there a built-in class that has functions that can return the list of running processes?是否有内置的 class 具有可以返回正在运行的进程列表的功能? 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.有一种方法可以使用Process()运行终端命令并执行/usr/bin/killall命令来终止进程,但我需要以编程方式执行此操作,因为使用应用程序运行终端命令不是一个好习惯。 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() .例如,删除文件也可以通过使用Process()运行终端命令来完成,而更好的方法是使用FileManager.default.remomveItem()

If you're looking for an application (rather than a process), then see NSWorkspace.shared.runningApplications .如果您正在寻找应用程序(而不是进程),请参阅NSWorkspace.shared.runningApplications You can call terminate() or forceTerminate() on those elements.您可以在这些元素上调用terminate()forceTerminate()

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).如果你想要一个所有 BSD 进程的列表(例如,你会从调用ps中得到什么),那是用sysctl完成的(Q&A 中的代码在 C;你必须将它包装到 Swift,或者重写它)。 I don't believe there's any Cocoa wrapper for that.我不相信有任何 Cocoa 包装器。 To kill a process, once you have its PID, use signal , which is what the kill Unix command uses.要杀死一个进程,一旦你有了它的 PID,就使用signal ,这就是kill Unix 命令所使用的。 Typically you want to send SIGTERM, which is a normal shutdown.通常你想发送 SIGTERM,这是一个正常的关机。 To force-kill a process, send SIGKILL.要强制终止进程,请发送 SIGKILL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM