LoginSignup
7
7

More than 5 years have passed since last update.

Electron で外部アプリの起動・停止を行う

Last updated at Posted at 2017-07-18

ElectronのGUIに起動・停止ボタンをつけて,外部アプリの起動・停止をしてみた.

検証環境

  • macOS Sierra 10.12.1
  • electron: ^1.4.8

起動&停止

execFile.app を実行し,ps aux でプロセス番号を取得する方法を試した.
execFileexec を同期的に実行すると,後者でプロセス番号が取得できない時があったので, 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)
7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7