Skip to content

Commit

Permalink
Better SIGINT handling in chrome-launcher (GoogleChrome/lighthouse#2959)
Browse files Browse the repository at this point in the history
  • Loading branch information
mikecardwell authored and paulirish committed Aug 17, 2017
1 parent 8e4e68a commit c5946e1
Showing 1 changed file with 21 additions and 6 deletions.
27 changes: 21 additions & 6 deletions chrome-launcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ const _SUPPORTED_PLATFORMS = new Set(['darwin', 'linux', 'win32']);

type SupportedPlatforms = 'darwin'|'linux'|'win32';

const instances = new Set();

export interface Options {
startingUrl?: string;
chromeFlags?: Array<string>;
Expand All @@ -46,22 +48,35 @@ export interface ModuleOverrides {
spawn?: typeof childProcess.spawn;
}

const sigintListener = async () => {
for (const instance of instances) {
await instance.kill();
}
process.exit(_SIGINT_EXIT_CODE);
};

export async function launch(opts: Options = {}): Promise<LaunchedChrome> {
opts.handleSIGINT = defaults(opts.handleSIGINT, true);

const instance = new Launcher(opts);

// Kill spawned Chrome process in case of ctrl-C.
if (opts.handleSIGINT) {
process.on(_SIGINT, async () => {
await instance.kill();
process.exit(_SIGINT_EXIT_CODE);
});
if (opts.handleSIGINT && instances.size === 0) {
process.on(_SIGINT, sigintListener);
}
instances.add(instance);

await instance.launch();

return {pid: instance.pid!, port: instance.port!, kill: async () => instance.kill()};
const kill = async () => {
instances.delete(instance);
if (instances.size === 0) {
process.removeListener(_SIGINT, sigintListener);
}
return instance.kill();
};

return {pid: instance.pid!, port: instance.port!, kill};
}

export class Launcher {
Expand Down

0 comments on commit c5946e1

Please sign in to comment.