[英]Electron kill process by process name on windows, mac(darwin) and linux
How can I kill processes by process names in Windows, Darwin, and Linux ?如何通过 Windows、Darwin 和 Linux 中的进程名称来终止进程? Like, assume the process I need to kill is 'vlc.exe' (basically close the application).
就像,假设我需要杀死的进程是'vlc.exe'(基本上关闭应用程序)。
Here is the function I wrote to check whether this process is running or not.这是我写的 function 来检查这个进程是否正在运行。
const isRunning = (query, cb) => {
let platform = process.platform;
let cmd = '';
switch (platform) {
case 'win32': cmd = `tasklist`; break;
case 'darwin': cmd = `ps -ax | grep ${query}`; break;
case 'linux': cmd = `ps -A`; break;
default: break;
}
exec(cmd, (err, stdout, stderr) => {
stdout = stdout.toLowerCase().replace(/\s/g, '');
cb({status: stdout.indexOf(query.toLowerCase()) > -1});
});
}
I call this function as我将此 function 称为
isRunning('vlc.exe', (vlc) => {
console.log({ vlc }); // true|false
});
So, I know that VLC is running or not.所以,我知道 VLC 是否正在运行。 Now I want to close it if it`s running.
现在我想在它运行时关闭它。 For windows its taskkill but for darwin and Linux?
对于 windows 它的taskkill但对于 darwin 和 Linux? Or is there any other way to kill processes?
或者有没有其他方法可以杀死进程?
The PID is in the ps
output. PID 在
ps
output 中。 If pidof
is available you could do kill $(pidof vlc)
.如果
pidof
可用,您可以kill $(pidof vlc)
。 Rather than write your own code to figure out PIDs and do the killing, you could also use a well-tested module for the same purpose.与其编写自己的代码来找出 PID 并进行杀戮,不如使用经过良好测试的模块来实现相同的目的。
On macOS and most probably on linux as well.在 macOS 上,很可能也在 linux 上。 process name is
VLC
.进程名称是
VLC
。 System are case sensitive so looking for vlc.exe
or vlc
will not find any running process.系统区分大小写,因此查找
vlc.exe
或vlc
将找不到任何正在运行的进程。
you can play around by doing something like你可以通过做类似的事情来玩
kill $(ps aux | grep -i 'vlc' | awk '{print $2}')
which will这将
ps aux
- look for all process ps aux
- 查找所有进程grep -i 'vlc'
filter ps out by capturing process with name VLC
or vlc
(think the -i parameter which force the case insensitive). grep -i 'vlc'
通过捕获名称为VLC
或vlc
的进程来过滤 ps(认为 -i 参数强制不区分大小写)。awk '{print $2}'
only capture the PID number. awk '{print $2}'
仅捕获 PID 号。kill
ask the system to graceful stop the process by given PID. kill
要求系统通过给定的 PID 优雅地停止进程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.