How to maintain command after exiting SSH?

倾然丶 夕夏残阳落幕 提交于 2019-12-11 18:22:19

问题


I am using PuTTy to run a node.js server on a shared host (cPanel). My question is whether it is possible to maintain a command even after I completely close PuTTy? My issue is that when I for example type 'nohup node server.js &' and my server runs successfully, the moment I close down PuTTy, my node server goes down again. I would love it if there was a way to continously have my node server running even after exiting PuTTy completely or even shutting down my computer.

I have tried the following things:
- nohup (as seen above), however that does not maintain the connection after I close down PuTTy.
- forever.js however still same issue as nohup.

Appreciate all the help I can get.

Edit: Just to clarify, my issue is not that I want the process to run in the background. My issue is whether it is possible to run the process even while my computer is shut down. It seems weird that I have to keep my PC on in order for the server process to continue, even though I'm using hosting.


回答1:


There are multiple ways to keep the command running in background even if you close the putty terminal.

  • Very simple one is that you put "&" at the end of command like following

    node server.js &

  • Second method is to use pm2. This is very efficient way to run the NodeJS server. It not only maintain session after closing terminal, but also if your operating system restarts, then it will automatically start the server again without user interaction to run the command.

    You can install pm2 by following command

    npm install pm2 -g

    And then start the node server as

    pm2 start server.js

Please update if this worked for you.




回答2:


You can use screen if it is available on the server.




回答3:


Probably you are looking for nohup or disown if need to run a process that won’t be terminated after closing the terminal:

$ nohup your command &
$ exit

Or using disown:

$ your command &
$ disown
$ exit

If you have multiple commands:

$ sleep 3600 &
$ sleep 86400 &

By typing jobs something like this appears:

[1]  - running    sleep 3600
[2]  + running    sleep 86400

To disown let’s say only job 2:

$ disown %2

If your process is already running, you can pause it ctrl+z, something like this will appear:

$ sleep 3600
^Z
zsh: suspended  sleep 3600

Then type bg to put it in background:

$ bg
[1]  + continued  sleep 3600

After that you can disown and exit:

$ disown
$ exit



回答4:


Found out the issue was with cPanel, as it did not support node.js. I moved to DigitalOcean and it worked fantastically there.



来源:https://stackoverflow.com/questions/51398353/how-to-maintain-command-after-exiting-ssh

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