🌳
pt0/serverF/childProcF/interactiveSpawnF.mts
1import * as _ from 'lodash-es'
2import { spawn, type StdioOptions } from 'child_process'
3import fs from 'fs'
5export const interactiveSpawn = async ({cmd, printCmd}: {cmd: string, printCmd?: string}) => {
6 console.log('intSpawn', printCmd || cmd)
7 return await new Promise((resolv, reject) => {
8 let stdio: StdioOptions = 'inherit'
9 let ttyFd: number | null = null
11 try {
12 ttyFd = fs.openSync('/dev/tty', 'r+')
13 stdio = [ttyFd, ttyFd, ttyFd]
14 } catch (err: any) {
15 if (err.code === 'ENXIO') {
16 console.warn('[interactiveSpawn] No TTY available, using inherited stdio')
17 } else {
18 throw err
19 }
20 }
22 const spawnObj = spawn(cmd, {shell: true, stdio})
23 spawnObj.on('close',(code: number | null)=>{
24 if (ttyFd !== null) {
25 fs.closeSync(ttyFd)
26 }
27 console.log('[shell] terminated :',code)
28 resolv({code})
29 })
30 })