如何按进程名称检查 mac 进程是否存在

How to check a mac process exists by process name

本文关键字:进程 是否 存在 mac 检查 何按 进程名      更新时间:2023-10-16

>我需要杀死一个 mac 进程,但在此之前我需要检查它是否真的存在?

我尝试使用C++方法system("killall process_name");按名称杀死进程。

但我想我还应该检查进程是否实际运行。 谁能告诉我,如何做到这一点?

BOOL processIsRunning = system("ps -Ac | grep 'AProcessName' > /dev/null") == 0;

或者,如果您特别要检查字符串:

BOOL processIsRunning = system("ps -ef | grep 'AUniqueString' | grep -iv grep > /dev/null") == 0;

您可以安全地使用killall - 您已经在使用的那个。它是无害的,即使该过程不存在。

既然你已经标记了Objective-C,我假设你对可可解决方案很好。如果您手头有进程名称,这是另一种杀死进程的简单方法。它使用苹果脚本。在这里,您无需检查它是否正在运行。

NSString *processName = @"Microsoft Outlook";
NSString *scriptSource = [NSString stringWithFormat:@"tell application "%@" to quit",processName];
NSAppleScript *script = [[NSAppleScript alloc] initWithSource:scriptSource];
[script executeAndReturnError:nil];