🌳
pt0/serverF/childProcF/live2SpawnF.mts
1import * as _ from 'lodash-es'
2import { spawn } from 'child_process'
5export const live2Spawn = async ({cmd, noOutCmd=false, usePty=false}: {cmd: string, noOutCmd?: boolean, usePty?: boolean}) => {
6 if (!noOutCmd) {
7 console.log(cmd)
8 }
10 return await new Promise<{exitCode: number | null, stdout: string, stderr: string, isSuccess: boolean}>((resolv, reject) => {
11 const spawnObj = (!process.stdout.isTTY && usePty)
12 ? spawn('script', process.platform === 'darwin'
13 ? ['-q', '/dev/null', '/bin/sh', '-c', cmd]
14 : ['-q', '-e', '-c', cmd, '/dev/null']
15 , {stdio: 'inherit'})
16 : spawn(cmd, {shell: true, stdio: 'inherit'})
18 let stdout = ''
19 let stderr = ''
21 const listenerFncs = _.map([
22 'SIGTERM',
23 'SIGQUIT',
24 'SIGINT'
25 ] as const, (sigStr) => {
26 const fnc = () => {
27 console.log(sigStr, 'efef203f9j3f9j9j')
28 spawnObj.kill(sigStr)
29 process.exit()
30 }
31 process.on(sigStr, fnc)
32 return [sigStr, fnc] as const
33 })
35 spawnObj.on('exit', function (exitCode) {
36 _.each(listenerFncs, ([sigStr, fnc]) => {
37 process.removeListener(sigStr, fnc)
38 })
39 const isSuccess = exitCode == 0
40 resolv({exitCode, stdout, stderr, isSuccess})
41 })
42 })
45export const live2SpawnThrow = async (props: {cmd: string, noOutCmd?: boolean, usePty?: boolean}) => {
46 const ret = await live2Spawn(props)
47 const {isSuccess} = ret
48 if (!isSuccess) {
49 throPtErr('!live2SpawnThrow', {...props, ret})
50 }
51 return ret