Welcome to OGeek Q&A 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...