0

我正在努力从 node 和 node-pty 获得我想要的行为。执行此代码后,节点似乎没有完全退出。寻找关于我所缺少的东西的提示。我已经将事情提炼成一个小例子来演示。当你执行代码时,它会产生 /bin/sh。一旦你退出那个 shell,它就会产生第二个 /bin/sh (以同样的方式)。退出该外壳后,节点将挂起。

let pty = require('node-pty');

main();

async function main() {
    let ptyProcess;

    console.log('Starting session 1');
    ptyProcess = pty.spawn('/bin/sh');
    await interact(ptyProcess);
    ptyProcess.kill();

    console.log('Starting session 2');
    ptyProcess = pty.spawn('/bin/sh');
    await interact(ptyProcess);
    ptyProcess.kill();

    console.log('Why won\'t I exit?');
}

function interact(ptyProcess) { // Allow user interaction from here on out
    return new Promise((resolve, reject) => {

        process.stdout.on('resize', () => {
            ptyProcess.resize(process.stdout.columns, process.stdout.rows);
        });

        process.stdin.on('data', data => {
            ptyProcess.write(data);
        });

        ptyProcess.on('data', data => {
            process.stdout.write(data);
        });

        ptyProcess.on('close', () => {
            console.log('Closing...');
            resolve();
        })
    });
}

示例会话:

MacBook-Pro:src mtwomey$ node demo.js
Starting session 1
sh-3.2$ exit
exit
exit
Closing...
Starting session 2
sh-3.2$ exit
exit
exit
Closing...
Why won't I exit?


[node remains running / open here]
4

1 回答 1

0

事实证明,这与 node-pty 完全无关。这是直接的 process.stdin。

process.stdin.unref() 是我需要的。

于 2020-06-07T03:25:30.433 回答