ElectronのGUIに起動・停止ボタンをつけて,外部アプリの起動・停止をしてみた.
検証環境
- macOS Sierra 10.12.1
- electron: ^1.4.8
起動&停止
execFile
で .app
を実行し,ps aux
でプロセス番号を取得する方法を試した.
execFile
と exec
を同期的に実行すると,後者でプロセス番号が取得できない時があったので, child-process-promise
をつかっている.
const {exec, execFile} = require('child-process-promise');
const kill = require('tree-kill');
const APP_PATH = 'path/to/app/test.app'
// ※ APP_NAMEの場合、同じ名前が含まれるプロセスが他に存在するとプロセスIDが正常に取得できない
// そのため APP_PATH で grep する方式に変更した
// const APP_NAME = 'test.app'
let pid = null;
// 起動
execFile('open', [APP_PATH])
.then(_ => exec(`ps aux | grep -v grep | grep -i ${APP_PATH} | awk '{print $2;}'`))
.then((result) => {
if (result.stderr) {
throw(result.stderr)
}
pid = parseInt(result.stdout);
logger.debug(`Start App name:${APP_PATH}, pid:${pid}`);
})
.catch((err) => {
logger.debug(`Error: ${JSON.stringify(err)}`);
});
// 停止
if(pid) {
kill(pid)
}
注意
spawn
を用いても起動はできるが,返り値のオブジェクトの情報だけだと.appのプロセス自体は取得できず,kill停止はできなかった.
const process = spawn('open', [APP_PATH])
// これらはspawnのプロセスであって(と思われる).app自体のプロセスではない
// test.appのPIDとは異なる
console.log(process.pid)
// killしても.appは落ちない
process.kill('SIGKILL')
kill(process.pid)