Writing the Linux/unix daemon

Source: Internet
Author: User
Tags syslog

Original: http://www.cnblogs.com/haimingwey/archive/2012/04/25/2470190.html

The daemon is widely used in the Linux/unix system. Sometimes, developers also want to turn their programs into daemons. When creating a daemon, you are exposed to a number of concepts such as child processes, process groups, meeting periods, signaling mechanisms, files, directories, and control terminals. Therefore, the daemon is still relatively complex, here in detail to discuss the Linux/unix of the Guardian process of writing, summed up eight experience, and give an example of the application.
Programming Essentials
1. Block some signals about the operation of the control terminal. Prevents 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. Execute the program into the background. As the daemon finally goes out of control terminal, it runs in the background. The method is to call fork in the process to terminate the parent process, allowing Daemon to execute in the background in the child process. This is often said to "shelling." The child process continuation function fork () is defined as follows:

#include <sys/types.h> #include <unistd.h> pid_t fork (void);

This function is a very important function in Linux/unix programming. It is called once, but returns two times. The difference between these two returns is that the return value of the child process is "0", and the parent process's return value is the ID of the child process. Returns "-1" If an error occurs.
3. Detach the control terminal, logon session, and process group. Developers who want to get rid of them and not be affected by them, typically use SETSID () to set up a new session's lead process and detach from the original logon session and process group. This is only one of the methods, there are also the following ways to deal with:

If  (fd = open ("/dev/tty", O_RDWR) >= 0) {ioctl (fd,tiocnotty,null); close (FD);}

Where/dev/tty is a streaming device and also a terminal mapping, calling the Close () function closes the terminal.
4. Disable the process to reopen the control terminal. The process has become a session leader without terminal, but it can reapply to open a control terminal. Developers can prevent a process from reopening the control terminal by not allowing the process to become a session leader, and the fork function needs to be called again.
The above program code indicates the end of the first child process, the second child process continues (the second child process is no longer the session leader).
5. Close the Open file descriptor and redirect the file descriptor for standard input, standard output, and standard error output. The process inherits the open file descriptor from the parent process that created it. If you do not close, you will waste system resources and cause unpredictable errors. The code for closing the three is as follows:

for (FD = 0, fdtablesize = getdtablesize ();  FD < fdtablesize; fd++)   Close (FD);

However, redirection of standard input, standard output, and standard error output is optional. Perhaps some programs want to keep the standard input (0), the standard output (1), and the standard error output (2), then the loop should bypass these three. The code is as follows:

For (fd =3, fdtablesize = Getdtablesize (), FD < fdtablesize; fd++)   Close (FD);

Some programs have special needs, and they need to redirect the three. Examples are as follows:

Error=open ("/tmp/error", o_wronly| o_creat,0600);  Dup2 (error,2); Close (error); In=open ("/tmp/in", o_rdonly| O_CREAT,0600); if (dup2 (in,0) ==-1)  perror ("in"); Close (in); Out=open ("/tmp/out", o_wronly| O_CREAT,0600); if (dup2 (out,1) ==-1) perror ("Out"); Close (out);

6. When changing the working directory to the root directory or a specific directory process activity, the file system in which the working directory resides cannot be removed.
It is generally necessary to change the working directory to the root directory or to a specific directory, noting that users need read and write access to this directory. Prevents Superuser from uninstalling the device when the system reports that the device is busy.
7. Process the SIGCHLD signal. The SIGCHLD signal is the signal sent to the kernel at the end of the child process.
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. Therefore, the SIGCHLD signal needs to be processed to reclaim the resources of the zombie process and avoid unnecessary waste of resources. You can use the following statement:
Signal (SIGCHLD, (void *) reap_status);
Capture the signal sigchld, and use the following function to process it:

void Reap_status ()  {int pid;    Union wait status;    while (PID = WAIT3 (&status,wnohang,null)) > 0)   ...}

8. Under Linux/unix, there is a syslogd daemon that provides a syslog () system call to the user. Any program can log events through the syslog.
Because Syslog is very handy and easy to configure, many programs use Syslog to send their logging information. The general daemon also uses syslog to output information to the system. Syslog has three functions, generally only need to use a syslog (...) function, Openlog ()/closelog () is optional. The syslog () is defined in Shslog.h as follows:

#include <syslog.h>void syslog (int priority,char *format,...);

Where the parameter priority indicates the level and purpose of the process to write information. The second parameter is a format string that specifies the format of the record output. At the end of this string you need to specify a%m that corresponds to the errno error code.
Application Examples
The following is an example of the application of the daemon of Linux under Programming, in Unix, different versions of the implementation of the details may be inconsistent, but the implementation of the principle is consistent with Linux.

#include <stdio.h> #include <signal.h> #include <sys/file.h> main (int Argc,char **argv) {  time_t Now;  int childpid,fd,fdtablesize;  int error,in,out;  /* Ignore terminal I/O signal, stop signal */signal (sigttou,sig_ign); Signal (sigttin,sig_ign);  Signal (sigtstp,sig_ign);   Signal (SIGHUP, sig_ign);  /* The parent process exits and the program runs in the background */  if (fork ()!=0) exit (1);   if (Setsid () <0) exit (1);/* Create a new Meeting Group///   ////* Child process exits, the grandchild process has no control terminal (*/    if (fork ()!=0) exit (1);  if (ChDir ("/tmp") ==-1) exit (1);/* Close Open file descriptor, including standard input, standard output, and standard error output */  for (FD = 0, fdtablesize = getdtablesize (); FD < fdtablesize; fd++)    Close (FD);   Umask (0);/* Reset File Creation Mask */    signal (sigchld,sig_ign);/* Ignore SIGCHLD signal */* Open LOG System *  /Syslog (log_user| Log_info, "daemon Test!n");     while (1)     {time      (&now);   Syslog (log_user| Log_info, "Current time: T%sttn", CTime (&now));    Sleep (6);     }   }

This program was compiled under Turbo Linux 4.0. This program is relatively simple, but basically embodies the daemon programming points. Readers for the actual application of different needs, but also can be adjusted accordingly.

http://liubin.itpub.net/post/325/24427 Source

Also refer to: http://topic.csdn.net/u/20080626/13/85947b12-b3a5-40eb-8e3b-2e1b9c3f0087.html

Writing the Linux/unix daemon

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.