How to prevent a background process from being stopped after closing SSH client in Linux

前端 未结 20 1309
悲&欢浪女
悲&欢浪女 2020-11-22 06:16

I\'m working on a Linux machine through SSH (Putty). I need to leave a process running during the night, so I thought I could do that by starting the process in background (

相关标签:
20条回答
  • 2020-11-22 06:51

    For most processes you can pseudo-daemonize using this old Linux command-line trick:

    # ((mycommand &)&)
    

    For example:

    # ((sleep 30 &)&)
    # exit
    

    Then start a new terminal window and:

    # ps aux | grep sleep
    

    Will show that sleep 30 is still running.

    What you have done is started the process as a child of a child, and when you exit, the nohup command that would normally trigger the process to exit doesn't cascade down to the grand-child, leaving it as an orphan process, still running.

    I prefer this "set it and forget it" approach, no need to deal with nohup, screen, tmux, I/o redirection, or any of that stuff.

    0 讨论(0)
  • 2020-11-22 06:51

    If you use screen to run a process as root, beware of the possibility of privilege elevation attacks. If your own account gets compromised somehow, there will be a direct way to take over the entire server.

    If this process needs to be run regularly and you have sufficient access on the server, a better option would be to use cron the run the job. You could also use init.d (the super daemon) to start your process in the background, and it can terminate as soon as it's done.

    0 讨论(0)
  • 2020-11-22 06:52

    On systemd/Linux, systemd-run is a nice tool to launch session-independent processes.

    0 讨论(0)
  • 2020-11-22 06:53
    nohup blah &
    

    Substitute your process name for blah!

    0 讨论(0)
  • 2020-11-22 06:57

    I would recommend using GNU Screen. It allows you to disconnect from the server while all of your processes continue to run. I don't know how I lived without it before I knew it existed.

    0 讨论(0)
  • 2020-11-22 06:57

    nohup is very good if you want to log your details to a file. But when it goes to background you are unable to give it a password if your scripts ask for. I think you must try screen. its a utility you can install on your linux distribution using yum for example on CentOS yum install screen then access your server via putty or another software, in your shell type screen. It will open screen[0] in putty. Do your work. You can create more screen[1], screen[2], etc in same putty session.

    Basic commands you need to know:

    To start screen

    screen


    To create next screen

    ctrl+a+c


    To move to next screen you created

    ctrl+a+n


    To detach

    ctrl+a+d


    During work close your putty. And next time when you login via putty type

    screen -r

    To reconnect to your screen, and you can see your process still running on screen. And to exit the screen type #exit.

    For more details see man screen.

    0 讨论(0)
提交回复
热议问题