Skip to content

Commit cc3bbfc

Browse files
committed
More cleanly kill Electron apps on exit
1 parent 56984af commit cc3bbfc

File tree

1 file changed

+29
-12
lines changed

1 file changed

+29
-12
lines changed

src/interceptors/electron.ts

Lines changed: 29 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { Interceptor } from '.';
1010

1111
import { HtkConfig } from '../config';
1212
import { delay, readFile } from '../util';
13+
import { windowsClose } from '../process-management';
1314
import { getTerminalEnvVars, OVERRIDES_DIR } from './terminal/terminal-env-overrides';
1415
import { reportError, addBreadcrumb } from '../error-tracking';
1516
import { findExecutableInApp } from '@httptoolkit/osx-find-executable';
@@ -142,21 +143,37 @@ export class ElectronInterceptor implements Interceptor {
142143

143144
await Promise.all(
144145
this.debugClients[proxyPort].map(async (debugClient) => {
145-
// Politely signal self to shutdown cleanly
146-
await debugClient.Runtime.evaluate({
147-
expression: 'process.kill(process.pid, "SIGTERM")'
146+
let shutdown = false;
147+
const disconnectPromise = new Promise((resolve) =>
148+
debugClient.once('disconnect', resolve)
149+
).then(() => {
150+
shutdown = true
148151
});
149152

150-
// Wait up to 1s for a clean shutdown & disconnect
151-
const cleanShutdown = await Promise.race([
152-
new Promise((resolve) =>
153-
debugClient.once('disconnect', () => resolve(true))
154-
),
155-
delay(1000).then(() => false)
156-
]);
153+
const pidResult = (
154+
await debugClient.Runtime.evaluate({
155+
expression: 'process.pid'
156+
}).catch(() => ({ result: undefined }))
157+
).result as { type?: string, value?: unknown } | undefined;
158+
159+
const pid = pidResult && pidResult.type === 'number'
160+
? pidResult.value as number
161+
: undefined;
162+
163+
// If we can extract the pid, use it to cleanly close the app:
164+
if (_.isNumber(pid)) {
165+
if (process.platform === 'win32') {
166+
await windowsClose(pid);
167+
} else {
168+
process.kill(pid, "SIGTERM");
169+
}
170+
171+
// Wait up to 1s for a clean shutdown & disconnect
172+
await Promise.race([disconnectPromise, delay(1000)]);
173+
}
157174

158-
if (!cleanShutdown) {
159-
// Didn't shutdown? Inject a hard exit.
175+
if (!shutdown) {
176+
// Didn't shutdown yet? Inject a hard exit.
160177
await debugClient.Runtime.evaluate({
161178
expression: 'process.exit(0)'
162179
}).catch(() => {}) // Ignore errors (there's an inherent race here)

0 commit comments

Comments
 (0)