A background job has some special characteristics:
- It keeps running after the session ends
- Its input/output are files instead of tty, so it doesn't have a control terminal
Although most daemon apps are written in a special way that they can run directly into background, any command can be ran as a background job on Linux.
1 Run a command in background from the very begining
Before we run a command, we already know that it needs to be running in background.We can:
$ nohup command &
Some guys may say, "hey, we can do the same thing without 'nohup'". So what's the difference between the following 2 command lines.
$ nohup command &
$ command &
"nohup" makes sure that the command will not exit after receiving SIGHUP signal. Normally when the shell session exits, it sends SIGHUP signal to all processes within the session. But it's configurable, so your shell may not send SIGHUP at all on exit, and if so, "nohup" can be omitted.
For bash, we can check this configuration by " shopt | grep hup".
$ shopt | grep hup
huponexit off
The above output means this bash will not send SIGHUP when it exits. So "command &" works well.
To make sure your command running in background whatever the configuration is, please use "nohup".
2 Put a already foreground running process into background
Sometimes, you run a command normally, and then realized that it should have been run as a background job. Don't worry, you still can put the running process into background.
- Press "Ctrl + z" to put the current process into background. But now the process will be suspended.
- run "bg" command to resume the suspended process.
- run "disown -h <jobid>" to make sure the shell will not send SIGHUP to this process in the future.
e.g.
$ ./1.sh
^Z
[1]+ Stopped ./1.sh
$ jobs -l
[1]+ 83372 Stopped ./1.sh
$ bg
[1]+ ./1.sh &
$ jobs -l
[1]+ 83372 Running ./1.sh &
$ disown -h 83372
$ jobs
[1]+ Running ./1.sh &
No comments:
Post a Comment