exec.js (2405B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2018 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 'use strict'; 20 21 // MODULES // 22 23 var execFile = require( 'child_process' ).execFile; 24 var logger = require( 'debug' ); 25 var cwd = require( '@stdlib/process/cwd' ); 26 var proc = require( './process.js' ); 27 28 29 // VARIABLES // 30 31 var debug = logger( 'parallel:worker:exec' ); 32 33 34 // MAIN // 35 36 /** 37 * Runs a script by executing the file in a child process without spawning a shell. 38 * 39 * @private 40 * @param {string} cmd - executable to run 41 * @param {string} script - script filepath 42 * @param {Callback} clbk - callback to invoke after a child process closes 43 * @returns {Process} child process 44 */ 45 function exec( cmd, script, clbk ) { 46 var child; 47 var args; 48 var opts; 49 50 debug( 'Creating child process...' ); 51 args = [ script ]; 52 opts = { 53 'cwd': cwd(), 54 'env': proc.env, 55 'encoding': proc.env.WORKER_ENCODING, 56 'maxBuffer': parseInt( proc.env.WORKER_MAX_BUFFER, 10 ), 57 'timeout': 0, 58 'killSignal': 'SIGTERM' 59 }; 60 if ( proc.env.WORKER_UID ) { 61 opts.uid = parseInt( proc.env.WORKER_UID, 10 ); 62 } 63 if ( proc.env.WORKER_GID ) { 64 opts.gid = parseInt( proc.env.WORKER_GID, 10 ); 65 } 66 child = execFile( cmd, args, opts, done ); 67 68 debug( 'Child process created. pid: %d.', child.pid ); 69 return child; 70 71 /** 72 * Callback invoked upon child process termination. 73 * 74 * @private 75 * @param {(Error|null)} error - error object 76 * @param {(Buffer|string)} stdout - standard output 77 * @param {(Buffer|string)} stderr - standard error 78 * @returns {void} 79 */ 80 function done( error, stdout, stderr ) { 81 if ( error ) { 82 debug( 'Child process error: %s. pid: %d.', error.message, child.pid ); 83 return clbk( error ); 84 } 85 debug( 'Child process closed. pid: %d.', child.pid ); 86 87 proc.stdout.write( stdout ); 88 proc.stderr.write( stderr ); 89 90 clbk( null, child.pid, script ); 91 } 92 } 93 94 95 // EXPORTS // 96 97 module.exports = exec;