69 lines
2.4 KiB
TypeScript
69 lines
2.4 KiB
TypeScript
import type { CommandDescriptor } from "@core/command";
|
|
import type { ShellState } from "@core/shell_state";
|
|
import { SIGNAL_MAP, type Signal } from "@core/signal";
|
|
import { EventEmitter } from "./event_emitter";
|
|
import { Process } from "./process";
|
|
import type { ShellEventMap } from "./shell";
|
|
|
|
export class ProcessManager {
|
|
private _Processes: Map<number, Process> = new Map();
|
|
private _PIDIndex: number = 0;
|
|
|
|
private _EventEmitter: EventEmitter<ShellEventMap> = new EventEmitter();
|
|
|
|
public createProcess(state: ShellState, descriptor: CommandDescriptor, args: string[]): number {
|
|
const pid = ++this._PIDIndex;
|
|
const process = new Process(pid, state, descriptor, args);
|
|
this._Processes.set(pid, process);
|
|
|
|
process.on("stdout", payload => this._EventEmitter.emit("stdout", payload));
|
|
process.on("stderr", payload => this._EventEmitter.emit("stderr", payload));
|
|
process.on("result", payload => {
|
|
this._Processes.delete(payload.pid);
|
|
this._EventEmitter.emit("result", payload);
|
|
});
|
|
|
|
this._EventEmitter.emit("process", { pid, name: descriptor.name });
|
|
process.execute();
|
|
|
|
return pid;
|
|
}
|
|
|
|
public sendSignal(pid: number, signal: Signal): void {
|
|
const process = this._Processes.get(pid);
|
|
|
|
if (!process) {
|
|
//Implement a proper error object later to return to shell
|
|
console.error("PID not found");
|
|
return;
|
|
}
|
|
|
|
process.sendSignal(signal);
|
|
}
|
|
|
|
public kill(pid: number): void {
|
|
const process = this._Processes.get(pid);
|
|
|
|
if (!process) {
|
|
//Implement a proper error object later to return to shell
|
|
console.error("PID not found");
|
|
return;
|
|
}
|
|
|
|
//Make global signals an enum later
|
|
process.sendSignal({ type: SIGNAL_MAP.SIGKILL } satisfies Signal);
|
|
}
|
|
|
|
public on<K extends keyof ShellEventMap>(type: K, handler: (payload: ShellEventMap[K]) => void): () => void {
|
|
return this._EventEmitter.on(type, handler);
|
|
}
|
|
|
|
public once<K extends keyof ShellEventMap>(type: K, handler: (payload: ShellEventMap[K]) => void): () => void {
|
|
return this._EventEmitter.once(type, handler);
|
|
}
|
|
|
|
public off<K extends keyof ShellEventMap>(type: K, handler: (payload: ShellEventMap[K]) => void): void {
|
|
this._EventEmitter.off(type, handler);
|
|
}
|
|
}
|