Linux --- Several methods of running programs in the background

Sometimes when we run a program, it takes a long time, so when we are about to get off work or when the network is unstable, we are more mad. Today I will share a few methods that I use at work to run programs in the background.

nohup 

$ nohup --h
Usage: nohup COMMAND [ARG]...
  or:  nohup OPTION
Run COMMAND, ignoring hangup signals.

      --help     display this help and exit
      --version  output version information and exit

 

When running a program, when we log out of the current account or close the terminal, the program will receive a SIGHUP signal. Nohup ignores this signal so that the program does not hang. The use of nohup is very simple, namely: nohup command. There are several tricks in the use process:

1. Use nohup and & at the same time

How to use: nohup command &

When exiting the current account or closing the terminal, the program will receive a SIGHUP signal, which will be ignored by programs that use nohup, but if CTRL + C is used to end the command, the program will receive a SIGINT signal, which will still make The program is terminated. If you don't want the program to be terminated, add a & at the end, so that the program also ignores the SIGINT signal

2. Redirect stdout and stderr

How to use: nohup command > filename 2<&1 &

Here 1 and 2 are file descriptors, 0 means stdin standard input, 1 means stdout standard output, 2 means stderr standard error, and a /dev/null means an empty device file.

Nohup will output the output to the nohup.out file by default. If you want to redirect the output to another file, you need to add > filename, 2<&1 after the nohup command, which means to redirect the standard error to the standard output.

setsid

$ setsid --h

Usage:
 setsid [options] <program> [arguments ...]

Run a program in a new session.

Options:
 -c, --ctty     set the controlling terminal to the current one
 -w, --wait     wait program to exit, and use the same return
 -h, --help     display this help and exit
 -V, --version  output version information and exit

  

nohup prevents the process from being interrupted midway by ignoring the HUP signal. If our process does not belong to the terminal child process that accepts the HUP signal, it will not be affected by the HUP signal. Using setsid helps us do this.

Usage: setsid command 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324788577&siteId=291194637