How to call execl, execle, execlp, execv, execvP or execvp from Node.js

POSIX systems provide a family of exec functions that allow you to load something that may be different into the current process, while maintaining open file descriptors, process ID, etc.

This can be done for a number of reasons, and in my case it is a reboot - I want to change the command line parameters of my own process and then restart it on an existing process so that there is no child process.

Unfortunately, to my great surprise, I could not find a way to call any of the exec* functions in Node.js. So, what is the correct way to replace the currently running Node.js process with another image?

0
javascript system-calls exec
source share
3 answers

I created a module to call the execvp function from NodeJS: https://github.com/OrKoN/native-exec

It works as follows:

 var exec = require('native-exec'); exec('ls', { newEnvKey: newEnvValue, }, '-lsa'); // => the process is replaced with ls, which runs and exits 

Since this is a native node addon, it needs a C ++ compiler. Works great on Docker, Mac OS, and Linux. Probably not working on Windows. Tested with node 6, 7 and 8.

+3
source share

I ended up using ffi and exporting execvp from libc .

+1
source share

Here is an example using node-ffi that works with v10 host. (alas, not v12)

 #!/usr/bin/node "use strict"; const ffi = require('ffi'); const ref = require('ref'); const ArrayType = require('ref-array'); const stringAry = ArrayType('string'); const readline = require("readline"); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question('Login: ', (username) => { username = username.replace(/[^a-z0-9_]/g, ""); rl.close(); execvp("/usr/bin/ssh", "-e", "none", username+'@localhost'); }); function execvp() { var current = ffi.Library(null, { execvp: ['int', ['string', stringAry]], dup2: ['int', ['int', 'int']]}); current.dup2(process.stdin._handle.fd, 0); current.dup2(process.stdout._handle.fd, 1); current.dup2(process.stderr._handle.fd, 2); var ret = current.execvp(arguments[0], Array.prototype.slice.call(arguments).concat([ref.NULL])); } 
0
source share

All Articles