Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How can I kill processes by process names in Windows, Darwin, and Linux? Like, assume the process I need to kill is 'vlc.exe' (basically close the application).

Here is the function I wrote to check whether this process is running or not.

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

isRunning('vlc.exe', (vlc) => {
    console.log({ vlc }); // true|false
});

So, I know that VLC is running or not. Now I want to close it if it`s running. For windows its taskkill but for darwin and Linux? Or is there any other way to kill processes?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.6k views
Welcome To Ask or Share your Answers For Others

1 Answer

The PID is in the ps output. If pidof is available you could do 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...