(vii) Learn about the process relationship and daemon of Unix Environment Advanced Programming (APUE)

Source: Internet
Author: User
Tags session id openlog syslog system log

.

.

.

.

.

Directory

(i) Learn the Unix Environment Advanced Programming (APUE) Standard IO

(ii) Study of UNIX Environment Advanced Programming (APUE) file IO

(iii) Learn about the Unix Environment Advanced Programming (APUE) files and directories

(iv) Learn about the Unix Environment Advanced Programming (APUE) system data files and information

(v) Learning about Unix Environment Advanced Programming (APUE) Process environment

(vi) The process Control of advanced Programming (APUE) for Unix environments

(vii) Learn about the process relationship and daemon of Unix Environment Advanced Programming (APUE)

Process relationship is the Nineth chapter of the third edition of Apue, the content of this chapter is usually of little significance to us, because it saga through a concept called "terminal", and now it is almost impossible to see the real terminal.

But it's impossible to explain the contents of Chapter 13th (daemon) without knowing this chapter, so we need to understand the relationship between terminal and process to understand what the daemon is.

Process relationship and daemon The two chapters are not much, and there are many associations, so we put the contents of the two chapters together to discuss.

Let's take a look at a few concepts.

1. Terminal

The real terminal is a "dumb device" that only receives input from the command and returns the result. You ask it 1+1=? It also does not know, it can only put your problem to the computer, and then the computer returned to show you the results.

It appears in the era of computers that are both expensive and huge. At that time, the computer was expensive, only one branch could afford it, the other company could not afford it, and some companies could only buy one, and the second was going bankrupt.

So expensive equipment if only to a person to use too wasteful, so that the computer can be used by many people, there is a terminal this device.

2. Sessions (session)

A successful terminal login is a session. The successful login of the shell is now equivalent to the successful login of the terminal at that time. A session is a container for a process group that can host one or more process groups.

3. Process Group

A process group is used to host a process, one or more processes in a process group, which is a collection of one or more processes (and can also be considered a container). A process not only has a unique PID, but also belongs to a process group.

How do I generate a process group? Very simple:

1 # Use a pipeline to generate a process group with a single command.  2ls more

The process group is divided into the foreground process group and the background process group.

There can be only one foreground process group or no foreground process group in a session.

Terminal equipment (such as the keyboard) can only communicate with the foreground process, can not communicate with the background process, according to the Convention, if the terminal device with a background process associated, it will kill the background process.

What is the foreground process group? For example, when you are packing with the tar command, you can no longer enter other commands. If the tar command executes for a long time, we'll add a & parameter to the back of the command and put it in the background to run.

The SID (session ID) column of the PS (1) command is the session ID that the program runs.

The process is first, and later people find that the process can be broken down into a number of small tasks executed separately, then there is the concept of threading, which is discussed in detail in the chapter of the later thread.

Now that the process has degenerated into a container, it exists to host threads. The PID appears to be a process number, which is actually consumed by the thread.

Processes and threads are just what we say, the kernel only sees threads, the kernel so-called process management is actually thread management, and the kernel always executes the task in the thread unit.

In summary: A session is used to host a process group that is used to host a process that the process uses to host threads.

The Nineth chapter is familiar with these concepts, remember the Myshell we mentioned earlier, using fork (2) + EXEC (3) + Wait (2) to implement a shell that can execute an external command. If you want to implement a shell that supports internal commands then you can study the contents of chapter Nineth carefully, and the main knowledge points of shell internal command processing are in chapter Nineth. We are not here in the Nineth chapter of the discussion so detailed, interested in the small partners can read their own books, what questions can be added to the blog above the mailing list discussed.

4.setsid (2)

1 Set Process Group ID 2 3 #include <unistd.h>45 pid_t setsid (void);

Create a session and set the ID of the process group. This function is the most valuable function we have in the 9th chapter, without which we cannot create a daemon later.

The caller cannot be the leader of the process group, the caller automatically becomes the new process group leader after the call, and the process ID will be set to the process group ID and session ID, so the daemon usually has the same PID, Pgid, SID, and is out of control terminal. The usual usage is the parent process fork (2) A child process, and then the child process calls Setsid (2) to turn itself into a daemon, and the parent process exits.

5. Daemon Process

Daemon Chestnut I will not write, because "Apue" the third edition P375 Figure 13-1 already has the detailed code, I for the book Chestnut summarizes.

Features of the daemon:

1) from the control Terminal, PS (1) AXJ TTY is a question mark (?).

2) is the leader of the process group, which is the same as the PID and Pgid.

3) There is usually no parent process, which is taken over by the number 1th init.

4) Create a new session, is the leader of the session, so the PID is the same as the SID.

Using the PS (1) AXJ command to view, PID, Pgid, SID the same process is the daemon.

The daemon can also use standard output, but it is not common sense, because the daemon does not control the terminal, so the daemon generally shuts down or redirects the standard input and output stream.

When we write the daemon, we switch the working path and switch it to a path that is bound to exist, such as/. Because it is assumed that your daemon was started on an unmounted device (such as a USB flash drive), the device cannot be uninstalled without modifying the work path.

The call to Umask (2) is to set the file-mode creation mask to a known value, because a mask that is inherited may be set to deny certain permissions and set if these permissions are required in the daemon.

For the chestnut on the book, there are two points to be spit:

1) The SIGHUP signal is used to notify the service process of soft restart, such as modifying a service configuration file can be sent to the service process SIGHUP signal to re-read the configuration file, so if there is no special requirements do not have to ignore the signal.

2) If there is no special requirement, you do not have to close all the file descriptors, just turn off standard input, standard output, and labeling errors.

6. System Log

The daemon should not use standard output, so what if the daemon needs to log some events or errors? It's going to be a system log.

The system log is generally kept in the/var/log/directory, but the log file permissions in this directory are almost only root to read and write, then the ordinary user's log how to write it? This requires the use of system log functions to write logs.

The root user is authorized to write logs specifically for the SYSLOGD service, and other programs need to log through a packaged set of function calls to the SYSLOGD service. This improves the security of the logs and prevents the log files from being tampered with illegally.

1Closelog, Openlog, syslog-send messages to the system logger2 3#include <syslog.h>4 5 voidOpenlog (Const Char*Ident,int option,int facility);6 voidSyslogint  Priority,Const Char* format, ...);7 voidCloselog (void);

The Openlog (3) function is not to open the log file but to establish a link to the SYSLOGD service to indicate that the current process is writing the log.

Parameter list:

  ident: Indicate your identity, by the programmer to specify, write anything is OK.

  option: to append anything to the log, multiple options are used with a bitwise OR link. Log_pid is the additional PID, this is the most commonly used.

  facility: The source of the message. You can typically specify only one.

Message source Meaning
Log_cron Messages from Scheduled Tasks
Log_daemon Message from daemon
Log_ftp Message from the FTP service
Log_kern Message from kernel
Log_user Default, general user-level messages

Table 1 Common required options for facility parameters

The syslog (3) function is used to submit the log contents, parameter list:

  Priority: Precedence. See the table below:

Level Meaning
Log_emerg "Critical" issues that are causing the system to be unavailable
Log_alert Situations in which "serious" must be dealt with immediately
Log_crit "Critical" condition
Log_err "Critical" error
Log_warning Warning
Log_notice Normal
Log_info Information
Log_debug Debugging

Table 2 log priority levels

Take Log_err as the dividing line, if you encounter the problem that the program cannot continue to run, report to Log_err above level (including Log_err).

If you encounter problems that do not affect the program to continue running, report log_err to the lower level.

Too many logs are sure to require a higher disk space, and too many useless logs can affect log auditing. Log files record which levels of logs are configured in the configuration file, and the default is that logs at or above the log_debug level are logged.

  Format: A formatted string similar to the printf (3) function. Be careful not to use the escape character \ n, otherwise the log will record a string "\ n" instead of a line feed.

... : The parameter of the placeholder in format.

Closelog (3) indicates the end of the log write.

7. Single Instance daemon

Some daemons need to have only one instance running at a time, which is called a single instance daemon. They create a process lock file under/var/run when they start, the daemon starts by judging if the lock file exists, if it already exists, and exits, if it does not exist, continue to run and create a lock file, and then delete it when exiting.

Daemons can be configured to auto-start scripts if they want to boot automatically:/etc/rc.d/rc.local

(vii) Learn about the process relationship and daemon of Unix Environment Advanced Programming (APUE)

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.