utilityProcess
utilityProcess는 Node.js와 Message 포트가 활성화된 자식 프로세스를 생성한다. Node.js의 child_process.fork API와 동일한 기능을 제공하지만, 크로미움의 Services API를 사용해 자식 프로세스를 실행한다.
프로세스: Main
메서드
utilityProcess.fork(modulePath[, args][, options])
modulePathstring - 자식 프로세스에서 실행할 스크립트의 경로를 지정한다.argsstring[] (선택 사항) - 자식 프로세스에서process.argv로 사용할 문자열 인자 목록이다.
반환 값: UtilityProcess
Class: UtilityProcess
UtilityProcess 인스턴스는 Node.js 통합 기능을 갖춘 Chromium에서 생성된 자식 프로세스를 나타낸다.
UtilityProcess는 EventEmitter를 상속받는다.
인스턴스 메서드
child.postMessage(message, [transfer])
messageanytransferMessagePortMain[] (선택 사항)
자식 프로세스로 메시지를 보낸다. 필요에 따라 하나 이상의 MessagePortMain 객체의 소유권을 이전할 수 있다.
예제:
// 메인 프로세스
const { port1, port2 } = new MessageChannelMain()
const child = utilityProcess.fork(path.join(__dirname, 'test.js'))
child.postMessage({ message: 'hello' }, [port1])
// 자식 프로세스
process.parentPort.once('message', (e) => {
const [port] = e.ports
// ...
})
child.kill()
boolean을 반환한다.
프로세스를 정상적으로 종료한다. POSIX 시스템에서는 SIGTERM을 사용하지만, 프로세스가 종료될 때 정리되도록 보장한다. 이 함수는 종료가 성공하면 true를 반환하고, 그렇지 않으면 false를 반환한다.
인스턴스 속성
child.pid
child.pid는 자식 프로세스의 프로세스 식별자(PID)를 나타내는 Integer | undefined 타입의 값이다. 자식 프로세스가 성공적으로 생성되기 전에는 이 값이 undefined로 설정된다. 자식 프로세스가 종료되면 exit 이벤트가 발생한 후 다시 undefined가 된다.
const child = utilityProcess.fork(path.join(__dirname, 'test.js'))
console.log(child.pid) // undefined
child.on('spawn', () => {
console.log(child.pid) // Integer
})
child.on('exit', () => {
console.log(child.pid) // undefined
})
참고: pid 값을 통해 현재 프로세스가 실행 중인지 확인할 수 있다.
child.stdout
child.stdout은 자식 프로세스의 stdout을 나타내는 NodeJS.ReadableStream | null 타입의 객체다. 자식 프로세스가 options.stdio[1]을 'pipe' 이외의 값으로 설정한 상태로 생성되었다면, 이 값은 null이 된다. 또한 자식 프로세스가 종료되면 exit 이벤트가 발생한 후에 이 값은 null로 설정된다.
// 메인 프로세스
const { port1, port2 } = new MessageChannelMain()
const child = utilityProcess.fork(path.join(__dirname, 'test.js'))
child.stdout.on('data', (data) => {
console.log(`Received chunk ${data}`)
})
child.stderr
child.stderr는 자식 프로세스의 표준 에러 출력을 나타내는 NodeJS.ReadableStream 또는 null 값이다. 자식 프로세스가 options.stdio[2]를 'pipe' 이외의 값으로 설정한 상태로 생성되었다면, 이 값은 null이 된다. 또한, 자식 프로세스가 종료되면 exit 이벤트가 발생한 후에는 이 값이 null로 설정된다.
인스턴스 이벤트
이벤트: 'spawn'
자식 프로세스가 성공적으로 생성되면 발생한다.
이벤트: 'error' 실험적 기능
반환값:
typestring - 에러 타입. 다음 값 중 하나:FatalError
locationstring - 에러가 발생한 소스 위치.reportstring - [Node.js 진단 보고서][].
V8에서 복구할 수 없는 에러로 인해 자식 프로세스가 종료되어야 할 때 발생한다.
error 이벤트를 수신하든 않든, 자식 프로세스가 종료된 후에는 exit 이벤트가 항상 발생한다.
이벤트: 'exit'
반환 값:
codenumber - 프로세스의 종료 코드를 포함한다. POSIX 시스템에서는 waitpid에서, Windows에서는 GetExitCodeProcess에서 얻은 값이다.
설명:
자식 프로세스가 종료된 후에 발생하는 이벤트이다.
이벤트: 'message'
반환값:
messageany
자식 프로세스가 process.parentPort.postMessage()를 사용하여 메시지를 보낼 때 발생한다.