forked from coder/code-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathipc.ts
More file actions
52 lines (46 loc) · 1.29 KB
/
ipc.ts
File metadata and controls
52 lines (46 loc) · 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import * as cp from "child_process";
import { Emitter } from "vs/base/common/event";
enum ControlMessage {
okToChild = "ok>",
okFromChild = "ok<",
}
export type Message = "relaunch";
class IpcMain {
protected readonly _onMessage = new Emitter<Message>();
public readonly onMessage = this._onMessage.event;
public handshake(child?: cp.ChildProcess): Promise<void> {
return new Promise((resolve, reject) => {
const target = child || process;
if (!target.send) {
throw new Error("Not spawned with IPC enabled");
}
target.on("message", (message) => {
if (message === child ? ControlMessage.okFromChild : ControlMessage.okToChild) {
target.removeAllListeners();
target.on("message", (msg) => this._onMessage.fire(msg));
if (child) {
target.send!(ControlMessage.okToChild);
}
resolve();
}
});
if (child) {
child.once("error", reject);
child.once("exit", (code) => {
const error = new Error(`Unexpected exit with code ${code}`);
(error as any).code = code;
reject(error);
});
} else {
target.send(ControlMessage.okFromChild);
}
});
}
public relaunch(): void {
if (!process.send) {
throw new Error("Not a child process with IPC enabled");
}
process.send("relaunch");
}
}
export const ipcMain = new IpcMain();