Skip to main content

utilityProcess

utilityProcess는 Node.js와 Message 포트가 활성화된 자식 프로세스를 생성한다. Node.js의 child_process.fork API와 동일한 기능을 제공하지만, 크로미움의 Services API를 사용해 자식 프로세스를 실행한다.

프로세스: Main

메서드

utilityProcess.fork(modulePath[, args][, options])

  • modulePath string - 자식 프로세스에서 실행할 스크립트의 경로를 지정한다.
  • args string[] (선택 사항) - 자식 프로세스에서 process.argv로 사용할 문자열 인자 목록이다.
  • options Object (선택 사항)
    • env Object (선택 사항) - 환경 변수의 키-값 쌍을 지정한다. 기본값은 process.env이다.
    • execArgv string[] (선택 사항) - 실행 파일에 전달할 문자열 인자 목록이다.
    • cwd string (선택 사항) - 자식 프로세스의 현재 작업 디렉토리를 지정한다.
    • stdio (string[] | string) (선택 사항) - 자식 프로세스의 stdoutstderr 모드를 설정한다. 기본값은 inherit이다. 문자열 값은 pipe, ignore, inherit 중 하나일 수 있다. 이 값들에 대한 자세한 내용은 Node.js의 stdio 문서를 참고한다. 현재 이 옵션은 stdoutstderrpipe, inherit, ignore로 설정할 수 있다. stdinignore 이외의 값으로 설정하면 오류가 발생한다. 예를 들어, 지원되는 값은 다음과 같이 처리된다:
      • pipe: ['ignore', 'pipe', 'pipe']와 동일
      • ignore: ['ignore', 'ignore', 'ignore']와 동일
      • inherit: ['ignore', 'inherit', 'inherit']와 동일 (기본값)
    • serviceName string (선택 사항) - 프로세스 이름을 지정한다. 이 이름은 app.getAppMetricsappchild-process-gone 이벤트에서 반환되는 ProcessMetricname 속성에 표시된다. 기본값은 Node Utility Process이다.
    • allowLoadingUnsignedLibraries boolean (선택 사항) macOS - 이 플래그를 사용하면 유틸리티 프로세스가 macOS에서 Electron Helper (Plugin).app 헬퍼 실행 파일을 통해 실행된다. 이 실행 파일은 com.apple.security.cs.disable-library-validationcom.apple.security.cs.allow-unsigned-executable-memory 권한으로 코드 서명할 수 있다. 이를 통해 유틸리티 프로세스가 서명되지 않은 라이브러리를 로드할 수 있다. 특별히 이 기능이 필요하지 않다면 비활성화하는 것이 좋다. 기본값은 false이다.
    • respondToAuthRequestsFromMainProcess boolean (선택 사항) - 이 플래그를 사용하면 net 모듈을 통해 생성된 모든 HTTP 401 및 407 네트워크 요청에 대해 기본 프로세스의 app#login 이벤트를 통해 응답할 수 있다. 기본적으로는 ClientRequest 객체의 login 이벤트를 사용한다. 기본값은 false이다.

반환 값: UtilityProcess

Class: UtilityProcess

UtilityProcess 인스턴스는 Node.js 통합 기능을 갖춘 Chromium에서 생성된 자식 프로세스를 나타낸다.

UtilityProcessEventEmitter를 상속받는다.

인스턴스 메서드

child.postMessage(message, [transfer])

  • message any
  • transfer MessagePortMain[] (선택 사항)

자식 프로세스로 메시지를 보낸다. 필요에 따라 하나 이상의 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' 실험적 기능

반환값:

  • type string - 에러 타입. 다음 값 중 하나:
    • FatalError
  • location string - 에러가 발생한 소스 위치.
  • report string - [Node.js 진단 보고서][].

V8에서 복구할 수 없는 에러로 인해 자식 프로세스가 종료되어야 할 때 발생한다.

error 이벤트를 수신하든 않든, 자식 프로세스가 종료된 후에는 exit 이벤트가 항상 발생한다.

이벤트: 'exit'

반환 값:

  • code number - 프로세스의 종료 코드를 포함한다. POSIX 시스템에서는 waitpid에서, Windows에서는 GetExitCodeProcess에서 얻은 값이다.

설명:

자식 프로세스가 종료된 후에 발생하는 이벤트이다.

이벤트: 'message'

반환값:

  • message any

자식 프로세스가 process.parentPort.postMessage()를 사용하여 메시지를 보낼 때 발생한다.