Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

javascript - 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? 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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...