node.js 通过进程名称检查进程是否正在运行,并结束进程

一、判断进程是否运行:

const execs = require('child_process').exec;

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;
    }
    execs(cmd, (err, stdout, stderr) => {
        cb(stdout.toLowerCase().indexOf(query.toLowerCase()) > -1);
    });
}

isRunning('Chrome.exe', (status) => {
    writer.write("\r\n__dirnamwwwwwwwwwwwwestatus--- " + status);
    console.log(status); // true|false
})

 二、获取进程详细信息

var ps = require('ps-node');

// A simple pid lookup
ps.lookup({
    command: 'node',
    psargs: 'ux'
    }, function(err, resultList ) {
    if (err) {
        throw new Error( err );
    }

    console.log(resultList.length);
    writer.write("\r\n__dirnamwwwwweresultList.length---" + resultList.length);
    resultList.forEach(function( process ){
        if( process ){
            console.log( 'PID: %s, COMMAND: %s, ARGUMENTS: %s', process.pid, process.command, process.arguments );
            writer.write("\r\n__dirwweprocess.pid---" + process.pid + "process.command= " + process.command);
        }
    });
});

 打印:

node.js 通过进程名称检查进程是否正在运行,并结束进程_第1张图片

打开任务管理器进程的详细信息,根据PID 就能找到运行的进程

三、通过进程名称检查进程是否正在运行,并结束进程

function viewProcessMessage (name, cb) {
  let cmd = process.platform === 'win32' ? 'tasklist' : 'ps aux'
  execs(cmd, function (err, stdout, stderr) {
    if (err) {
      return console.error(err)
    }
    stdout.split('\n').filter((line) => {
      let processMessage = line.trim().split(/\s+/)
      let processName = processMessage[0] //processMessage[0]进程名称 , processMessage[1]进程id
      if (processName === name) {
        return cb(processMessage[1])
      }
    })
  })
}

viewProcessMessage('Chrome.exe',function (msg) {
    writer.write("\r\n__viewProcessMessage--- " + msg);
  //关闭匹配的进程
  process.kill(msg);
})

你可能感兴趣的:(node.js,javascript,前端,node.js)