Original: http://blog.csdn.net/lovemdx/article/details/20529563
- SIGHUP
- Nohup
- Running in the background
- Daemon
Today and colleagues talk about this problem, I looked up the relevant information, the total is as follows
Mention of these three is because we run the program in the Linux terminal, there is hope not because the terminal's exit or abnormal disconnection causes the running program to exit the need. The reason why the terminal exits abnormally disconnects the program is because it sends a SIGHUP signal to a program running in the terminal.
SIGHUP
About Sighup, the following is an excerpt from Baidu Encyclopedia
Unix process Fabric for a session contains a foreground process group and one or more background process groups , and a process group contains multiple processes.
A session may have a session first process, and a session header process may have a control terminal.
A process group may have a process group first process. The process ID of the process group 's first process is equal to the process group ID .
Here is possible, under certain circumstances is not.
The process of interacting with the terminal is the foreground process, or the background process
SIGHUP will be sent to the appropriate process in the following 3 scenarios :
1. when the terminal is closed , the signal is sent to the session first process and the process submitted as the job (i.e. the process submitted with the & symbol)
2.when the session first process exits , the signal is sent to each process in the foreground process group in the session
3. If the parent process exits causes the process group to become an orphan process group and there are processes in the process group that are in a stopped state (receive SIGSTOP or sigtstp signal), the signal is sent to each process in the process group.
The system 's default processing of the SIGHUP signal is to terminate the process of receiving the signal. So if the signal is not captured in the program, the process exits when the signal is received.
Can look at the sighup signal and control terminal, analysis of very good.
Nohup
See links: Usage of the nohup command clear
Purpose: To run the command without hanging off.
Syntax: Nohup Command [Arg ...] [&]
Description: The nohup command runs commands specified by the command parameter and any related ARG parameters, ignoring all hang-up (SIGHUP) signals. Use the Nohup command to run a program in the background after logging off. To run the Nohup command in the background, add & (the symbol representing "and") to the end of the command.
The output is appended to the Nohup.out file in the current directory, regardless of whether the output of the Nohup command is redirected to the terminal. If the nohup.out file for the current directory is not writable, the output is redirected to the $HOME/nohup.out file. If no file can be created or opened for appending, then the command specified by the commands parameter is not callable. If the standard error is a terminal, then all output of the specified command to the standard error is redirected to the same file descriptor as the standard output.
Exit Status: The command returns the following exit values:
126 you can find but not invoke commands specified by the command parameter.
The 127nohup command has an error or cannot find the command specified by the commands parameter.
Otherwise, the exit status of the Nohup command is the command parameter that specifies the exit state of the commands.
Nohup command and its output file
Nohup command: If you are running a process and you feel that the process will not end when you exit the account, you can use the Nohup command. This command can continue to run the process after you exit the account/close the terminal. Nohup is the meaning of not hanging (n ohang up).
The general form of the command is: Nohup Command &
To submit a job using the Nohup command
If you submit a job using the Nohup command, all output from the job is redirected to a file named Nohup.out by default, unless the output file is specified separately:
Nohupcommand > Myout.file 2>&1 &
In the example above, the output is redirected to the Myout.file file.
Through Nohup source analysis, we can see that the essence of nohup is by ignoring the sighup signal , which will not be exited when the terminal closes due to the SIGHUP signal causes the program to exit. Nohup additional features the output is appended to the Nohup.out file in the current directory, regardless of whether the output of the Nohup command is redirected to the terminal. If the nohup.out file for the current directory is not writable, the output is redirected to the $HOME/nohup.out file.
Nohup itself does not put the program in the background, but the program started by Nohup mode, because it ignores the sighup signal, it receives the SIGHUP signal will not exit.
& Background Run
is to keep the program running in the background. For the shell, a program can be run in the background by &. It is run as a job. At this point, if the terminal is disconnected, the program will still be sighup signal to exit. That is the first scene of the sighup signal above.
However, if the exit command is executed in the terminal at this point, the current main process exits. This allows the background execution of the program to become an orphan process, thus being taken over by the INIT process. At this point, the terminal can be disconnected and will not be sighup signal. That is, even if the terminal is disconnected, the program will run. That's why after we execute a program in a shell script through &, the shell script executes, and even if the terminal is disconnected, the shell script-initiated daemon does not exit. Since the shell was executed, the program it started became an orphan process and was taken over by Init.
Daemon
The daemon process is the daemon, and most of the Linux service processes are implemented through the daemon process. For example, process number No. 0 (scheduling process), Process 1th (init process). From its name guardian to see that it is generally the machine started on the run, shut down before the stop. So it should not be affected by the terminal. At the same time actually running in the background.
In the current Linux has provided an API can be called directly to the process can be changed to the daemon: the function is described as follows: you can see http://man7.org/linux/man-pages/man3/daemon.3.html
int daemon (int __nochdir, int __noclose);
If the value of __nochdir is 0, the working directory will be switched to the root directory;
If __noclose is 0, the standard input, output, and standard errors are redirected to/dev/null.
Use is very simple: a simple example is as follows:
#include <unistd.h>
#include <stdio.h>
int Do_sth ()
{
//addwhat u Want
return 0;
}
int main ()
{
Daemon (0,0);
while (1)
{
Do_sth ();
Sleep (1);
}
}
Compile and run
[Leconte@Localhostdaemon]$ gcc -o test test.c
[Leconte@Localhostdaemon]$. /test
And most of them need to implement their own, on the daemon programming points on the Web many, summarized as follows: see the Linux daemon programming method
1. Block some signals about the operation of the control terminal. This is to prevent the control terminal from interfering with exiting or suspending when the daemon is not functioning properly. Examples are as follows:
Signal (sigttou,sig_ign);
Signal (sigttin,sig_ign);
Signal (sigtstp,sig_ign);
Signal (sighup,sig_ign);
All the signals have their own names. These names start with the "SIG", but they are different later. These names allow developers to learn what's going on in the system. When the signal appears, the developer can ask the system to do the following three actions:
Ignore the signal. Most of the signals are handled this way, and this usage is used here. It is noteworthy, however, that Sigkill and sigstop signals cannot be ignored for processing.
Capture the signal. The most common case is if the sigchid signal is captured, it indicates that the child process has been terminated. You can then call the Waitpid () function in the capture function of this signal to get the process ID of the child process and its terminating state. Also, if a process creates a temporary file, it is necessary to write a signal capture function for the process termination signal sigterm to clear the temporary files.
Executes the default action of the system. For most signals, the default action of the system is to terminate the process. The signal for these terminals is generally ignored and the terminal is protected from interference.
Such signals are, Sigttou (for background process write control terminal), Sigttin (for background process read Control terminal), SIGTSTP (for terminal hangs), and sighup (sent to all meeting members when the process leader exits).
2. Running in the background: to prevent it from suspending (or occupying) the terminal, it should be run in the background, by fork, and then by exiting the process.
3. Out-of-control terminal, logon session, and process group: The process belongs to the process group, and the process group number is the process number of the process leader. A logged-on session can contain multiple process groups. These process groups share a control terminal. This control terminal is the login terminal of the creation process. Control terminals, logon sessions, and process groups are inherited from the parent process at fork. We need to get rid of them and make them unaffected, by calling Setsid () on a 1 basis to make the process a conversation leader.
Setsid ();
Description: The Setsid () call failed when the process was the session leader. But the 1th has ensured that the process is not a conversation leader. After the Setsid () call succeeds, the process becomes the new session leader and the new process leader, and is detached from the original logon session and process group. Due to the exclusivity of the session process to the control terminal, the process is disconnected from the control terminal at the same time.
4. Prohibit the process from reopening the control terminal: ( Note: This step is online for daemon differences, some think it is not necessary, some think it is necessary) the current process is a non-terminal session leader, but the conversation leader can re-apply to open a control terminal. And we can prevent the process from reopening the control terminal by making the process no longer a session leader. The way is to fork () again and exit the parent process. Use its child process (the parent process of the child process is the conversation leader, and it is certainly not the conversation leader)
5. Close Open File descriptor: Because the fork inherits the file descriptor that the parent process opens, if you do not close it, you will waste system resources, cause the file system where the process resides to fail to unload and cause other unpredictable errors, so shut them down:
6. Change the current working directory: The process room, the working directory of the file system can not be uninstalled, generally need to change the working directory to the directory, and for the need to dump the core, the process of writing to run the log to change the working directory to a specific directory, such as/tmp. ChDir ("/tmp")
7. Reset File Mask: The Reset file creation mask process inherits the file creation mask from the parent process that created it. It may modify the access bit of the file created by the daemon. To prevent this, the file creation mask is cleared: umask (0);
8. Processing SIGCHLD signal: processing SIGCHLD signal
Processing SIGCHLD signals is not a must. However, for some processes, in particular, server processes often generate child processes to process requests when requests arrive. If the parent process does not wait for the child process to end, the child process becomes a zombie process (zombie) and thus consumes system resources. If the parent process waits for the child process to end, it increases the burden on the parent process and affects the concurrency performance of the server process. The operation of the SIGCHLD signal can be easily set to Sig_ign under Linux.
Signal (sigchld,sig_ign);
This way, the kernel does not spawn a zombie process at the end of the child process. Unlike BSD4, the BSD4 must explicitly wait for the child process to end before releasing the zombie process.
What is the difference between a daemon and a background run program with & end?
The biggest difference has several points:1) The daemon has completely detached from the terminal console, the program is not completely out of the terminal, before the terminal is not closed or will be output to the terminal2) The daemon will not be affected when the terminal console is closed, and the latter program will stop with the user exiting and need to run in Nohup XXX & format to avoid impact3) The session group and current directory of the daemon, file descriptors are independent. Running in the background is just a fork in the terminal, so the program executes in the background, and none of this changes.
as long as the sighup is ignored, we can reach the end of the terminal we need to continue to execute . So is it possible to send a sighup signal to our backstage jobs when we exit SSH, when we execute the shell? if the sighup signal is sent, all processes running under the shell will be terminated, that is, the desired background execution is not implemented. In the shell options, there is huponexit this option, meaning that when exiting the shell, whether to send this sighup signal?
$ shopt
Cdable_vars off
Cdspell off
Checkhash off
Checkwinsize off
Cmdhist on
Dotglob off
Execfail off
Expand_aliases on
Extdebug off
Extglob off
Extquote on
Failglob off
Force_fignore on
Gnu_errfmt off
Histappend off
Histreedit off
Histverify off
Hostcomplete on
Huponexit off
Interactive_comments on
Lithist off
Login_shell on
Mailwarn off
No_empty_cmd_completion off
Nocaseglob off
Nocasematch off
Nullglob off
Progcomp on
Promptvars on
Restricted_shell off
Shift_verbose off
SourcePath on
Xpg_echo off
The default option above, huponexit off, in this case, when you exit the shell, the background program will continue to run,
http://blog.csdn.net/hepeng597/article/details/9816751
http://blog.163.com/sparkle_tiangz/blog/static/1175902032011101011818771/
Http://www.cnblogs.com/xiaouisme/archive/2012/08/07/2627456.html
http://my.oschina.net/beiyou/blog/76226
Http://www.cnblogs.com/SuperXJ/archive/2011/10/31/2230314.html