In Linux, how to prevent a background process from

2018-12-31 19:31发布

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 (with an ampersand at the end of the command) and redirecting stdout to a file. To my surprise, that doesn't work. As soon as I close the Putty window, the process is stopped.

How can I prevent that from happening??

20条回答
妖精总统
2楼-- · 2018-12-31 19:58

When the session is closed the process receives the SIGHUP signal which it is apparently not catching. You can use the nohup command when launching the process or the bash built-in command disown -h after starting the process to prevent this from happening:

> help disown
disown: disown [-h] [-ar] [jobspec ...]
     By default, removes each JOBSPEC argument from the table of active jobs.
    If the -h option is given, the job is not removed from the table, but is
    marked so that SIGHUP is not sent to the job if the shell receives a
    SIGHUP.  The -a option, when JOBSPEC is not supplied, means to remove all
    jobs from the job table; the -r option means to remove only running jobs.
查看更多
与风俱净
3楼-- · 2018-12-31 19:59

As others have noted, to run a process in the background so that you can disconnect from your SSH session, you need to have the background process properly disassociate itself from its controlling terminal - which is the pseudo-tty that the SSH session uses.

You can find information about daemonizing processes in books such as Stevens' "Advanced Network Program, Vol 1, 3rd Edn" or Rochkind's "Advanced Unix Programming".

I recently (in the last couple of years) had to deal with a recalcitrant program that did not daemonize itself properly. I ended up dealing with that by creating a generic daemonizing program - similar to nohup but with more controls available.

Usage: daemonize [-abchptxV][-d dir][-e err][-i in][-o out][-s sigs][-k fds][-m umask] -- command [args...]
  -V          print version and exit
  -a          output files in append mode (O_APPEND)
  -b          both output and error go to output file
  -c          create output files (O_CREAT)
  -d dir      change to given directory
  -e file     error file (standard error - /dev/null)
  -h          print help and exit
  -i file     input file (standard input - /dev/null)
  -k fd-list  keep file descriptors listed open
  -m umask    set umask (octal)
  -o file     output file (standard output - /dev/null)
  -s sig-list ignore signal numbers
  -t          truncate output files (O_TRUNC)
  -p          print daemon PID on original stdout
  -x          output files must be new (O_EXCL)

The double-dash is optional on systems not using the GNU getopt() function; it is necessary (or you have to specify POSIXLY_CORRECT in the environment) on Linux etc. Since double-dash works everywhere, it is best to use it.

You can still contact me (firstname dot lastname at gmail dot com) if you want the source for daemonize.

However, the code is now (finally) available on GitHub in my SOQ (Stack Overflow Questions) repository as file daemonize-1.10.tgz in the packages sub-directory.

查看更多
零度萤火
4楼-- · 2018-12-31 19:59

Accepted answer suggest using nohup. I would rather suggest using pm2. Using pm2 over nohup has many advantages, like keeping the application alive, maintain log files for application and lot more other features. For more detail check this out.

To install pm2 you need to download npm. For Debian based system

sudo apt-get install npm

and for Redhat

sudo yum install npm

Or you can follow these instruction. After installing npm use it to install pm2

npm install pm2@latest -g

Once its done you can start your application by

$ pm2 start app.js              # Start, Daemonize and auto-restart application (Node)
$ pm2 start app.py              # Start, Daemonize and auto-restart application (Python)

For process monitoring use following commands:

$ pm2 list                      # List all processes started with PM2
$ pm2 monit                     # Display memory and cpu usage of each app
$ pm2 show [app-name]           # Show all informations about application

Manage processes using either app name or process id or manage all processes together:

$ pm2 stop     <app_name|id|'all'|json_conf>
$ pm2 restart  <app_name|id|'all'|json_conf>
$ pm2 delete   <app_name|id|'all'|json_conf>

Log files can be found in

$HOME/.pm2/logs #contain all applications logs

Binary executable files can also be run using pm2. You have to made a change into the jason file. Change the "exec_interpreter" : "node", to "exec_interpreter" : "none". (see the attributes section).

#include <stdio.h>
#include <unistd.h>  //No standard C library
int main(void)
{
    printf("Hello World\n");
    sleep (100);
    printf("Hello World\n");

    return 0;
}

Compiling above code

gcc -o hello hello.c  

and run it with np2 in the background

pm2 start ./hello
查看更多
情到深处是孤独
5楼-- · 2018-12-31 20:00

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.

查看更多
永恒的永恒
6楼-- · 2018-12-31 20:00

Use screen. It is very simple to use and works like vnc for terminals. http://www.bangmoney.org/presentations/screen.html

查看更多
路过你的时光
7楼-- · 2018-12-31 20:05

I used screen command. This link has detail as to how to do this

https://www.rackaid.com/blog/linux-screen-tutorial-and-how-to/#starting

查看更多
登录 后发表回答