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

蹲街弑〆低调 提交于 2019-12-24 14:55:04

问题


POSIX systems expose family of exec functions, that allow one to load something maybe different into current process, keeping open file descriptors, process identifier and so on.

This can be done for variety of reasons, and in my case this is bootstrapping — I want to change command line options of my own process, and then reload it over existing process, so there would be no child process.

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


回答1:


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

It works like this:

var exec = require('native-exec');

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

Since it's a native node addon it requires a C++ compiler installed. Works fine in Docker, on Mac OS and Linux. Probably, does not work on Windows. Tested with node 6, 7 and 8.




回答2:


I ended up using ffi module, and exported execvp from libc.




回答3:


Here is an example using node-ffi that works with node v10. (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]));    
}


来源:https://stackoverflow.com/questions/34290403/a-way-to-call-execl-execle-execlp-execv-execvp-or-execvp-from-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!