简体   繁体   中英

Node.js process restart

I wanna know if theres a general function or can be made a function to restart the process; just like process.disconnect() but in this case it will restart the script when the function is called.

Generally process managers are used to (automatically) restart processes, such as monit, PM2, nodemon, forever, etc.

However, you could restart from the process itself by simply spawning a detached child process that waits some period of time and then executes the same script. You could do this as a combination of two commands, one to sleep and the other the current command line, or you could simply incorporate the sleep into your script. An example of the latter:

var spawn = require('child_process').spawn;

(function main() {

  if (process.env.process_restarting) {
    delete process.env.process_restarting;
    // Give old process one second to shut down before continuing ...
    setTimeout(main, 1000);
    return;
  }

  // ...

  // Restart process ...
  spawn(process.argv[0], process.argv.slice(1), {
    env: { process_restarting: 1 },
    stdio: 'ignore'
  }).unref();
})();

On Windows, you may need to add detached: true to your spawn() configuration object though. For *nix, this usually shouldn't be necessary.

One thing to keep in mind though is that any restarted process won't have access to the terminal anymore, if the original process was started in the foreground.

Also, you could eliminate the delay and process.env checking if your script does not use any resources that can only be used by at most one process at any given time.

One final note: if your process crashes abnormally, due to memory exhaustion, triggering a C++ assertion, a V8 bug, etc., your process won't restart obviously (even if you have an 'unhandledException' event handler set for process ). To account for these situations you pretty much need some sort of external mechanism to restart the process.

万一您将脚本作为系统守护程序启动(例如,使用upstart或systemd),则可以只使用process.exit()并让它们负责为您重新创建一个新进程。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM