问题
I have a PHP server which is the main application. I have a Nodejs Server which is a sub-application.
Nodejs Server is used for a Notification Mechanism. I want to be able to disable the notification mechanism from my main application which runs on PHP.
There is a button. On clicking it, I change my Nodejs config file and now I want to restart Nodejs server. I imagine I can do something like this in PHP:
exec("kill sudo lsof -t -i:4849
");
exec("node server.js");
Prospective problems: 1)Permissions issue : I imagine this could be solved by giving my apache user the ownership of node application. Am I right? 2)Exec : Doing an exec causes my browser to go on loading. I do netstat and find the Nodejs server running. This is the problem that is worrying me. I suppose I need to do some fork and exec method so that the child process(Nodejs ) runs independently.
Please help.
Solution :
exec("fuser -k ". NODEAPPPORT ."/tcp > /dev/null 2>&1 &");
exec('bash -c "exec nohup setsid node "'.NODEPATH.'/app.js" >
/dev/null 2>&1 &"');
I redirected the stdout and stderr to /dev/null. I run it as an independent process.It works like a charm.
回答1:
My suggestion would be: don't.
Run the Node server as a standalone server, either through a framework such as Express or something else. You could then expose your Node app's endpoint(s) (which would be the simplest solution IMO) via a private network and/or use a simple authorization mechanism between your PHP app and your Node app. You can then start/stop the notification system via that simple API endpoint instead of killing/restarting your Node app every time. Suppose that it crashes upon startup for whichever reason, you wouldn't be able to tell that it's down from your PHP app.
I don't know how exactly your notifications app works, but I'm guessing it's handling some sort of a stream which you can easily turn off without killing the entire Node server.
来源:https://stackoverflow.com/questions/54243429/how-to-run-nodejs-server-from-php-script