Skip to content

Commit

Permalink
wait for fd close
Browse files Browse the repository at this point in the history
  • Loading branch information
jackyzha0 committed Oct 24, 2024
1 parent 00dadbb commit 1e37466
Showing 1 changed file with 19 additions and 11 deletions.
30 changes: 19 additions & 11 deletions wrapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,13 +53,17 @@ export class Pty {
constructor(options: PtyOptions) {
const realExit = options.onExit;

let resolve: (value: ExitResult) => void;
let exitResult: Promise<ExitResult> = new Promise((res) => {
resolve = res;
let markExited: (value: ExitResult) => void;
let exitResult: Promise<ExitResult> = new Promise((resolve) => {
markExited = resolve;
});
let markFdClosed: () => void;
let fdClosed = new Promise<void>((resolve) => {
markFdClosed = resolve;
});
const mockedExit = (error: NodeJS.ErrnoException | null, code: number) => {
console.log('mocked exit')
resolve({ error, code });
markExited({ error, code });
};

// when pty exits, we should wait until the fd actually ends (end OR error)
Expand All @@ -74,20 +78,24 @@ export class Pty {
this.write = new WriteStream(this.#fd);

// catch end events
const handleEnd = () => {
const handleEnd = async () => {
if (this.#fdEnded) {
return;
}

this.close();
this.#fdEnded = true;
exitResult.then((result) => {
console.log('calling real exit')
realExit(result.error, result.code)
});

// must wait for fd close and exit result before calling real exit
await fdClosed;
const result = await exitResult;
console.log('calling real exit')
realExit(result.error, result.code)
}

this.read.on('end', handleEnd);
this.read.on('close', () => {
markFdClosed();
});

// PTYs signal their done-ness with an EIO error. we therefore need to filter them out (as well as
// cleaning up other spurious errors) so that the user doesn't need to handle them and be in
Expand All @@ -107,7 +115,7 @@ export class Pty {
// error so far, we are considered to be in good standing.
console.log('eio')
this.read.off('error', handleError);
handleEnd();
markFdClosed();
return;
}
}
Expand Down

0 comments on commit 1e37466

Please sign in to comment.