(7) learning the process relationship and daemon of APUE in Unix environment together, And apue in Advanced Programming

Source: Internet
Author: User
Tags openlog

(7) learning the process relationship and daemon of APUE in Unix environment together, And apue in Advanced Programming

.

.

.

.

.

Directory

(1) learning standard IO for advanced programming in Unix environment (APUE) together

(2) learning together the file IO of advanced programming in Unix environment (APUE)

(3) Learning Together files and directories of advanced programming in Unix environments (APUE)

(4) Studying the system data files and information of advanced programming in Unix environment (APUE) together

(5) learning the process environment of advanced programming in Unix environment (APUE) together

(6) Process Control for advanced programming (APUE) in Unix environment

(7) learning the process relationship and daemon process of advanced programming in Unix environment (APUE) together

 

 

Process relationship is the ninth chapter of the third edition of APUE. The content of this chapter is usually of little significance to us, because it involves a concept called"Terminal"But now it is almost impossible to see the real terminal.

However, if you do not understand this chapter, you cannot explain chapter 1 (Daemon). You must understand the relationship between the terminal and the process to understand what the daemon process is.

There are not many links between the process relationship and the daemon, so we will discuss the two chapters together.

Let's take a look at several concepts.

1. Terminal

In a real sense, a terminal is a "stupid device". It can only receive command input and return results. You ask it 1 + 1 =? It does not know, it can only pass your problem to the computer, and then display the results returned by the computer to you.

It appeared in the age when computers were expensive and huge. At that time, computers were expensive to the extent that only some companies could afford and other companies could not afford, and some companies could only buy one, and the second was about to go bankrupt.

Therefore, it is a waste of money to use such expensive devices only for one person. Therefore, in order to allow computers to be used by many people, devices such as terminals may appear.

 

2. Session)

A successful terminal login is a session. Now a successful shell login is equivalent to a successful terminal login at that time. A session is equivalent to a process group container. It can hold one or more Process Groups.

 

3. Process Group

A process group is used to host processes. A process group contains one or more processes, which are a collection of one or more processes (or containers ). A process not only has a unique PID, but also belongs to a process group.

How to generate a process group? Simple:

1 # use a pipeline to generate a process group using a command. 2 ls | more

 

The process group consists of the foreground process group and background process group.

A session can have only one foreground process group or no foreground process group.

A terminal device (such as a keyboard) can only communicate with the foreground process and cannot communicate with the background process. As agreed, if the terminal device is associated with a background process, the background process will be killed.

What is a foreground process group? For example, when you are using the tar command for packaging, you cannot enter other commands. If the tar command is executed for a long time, we will add an & parameter to the command and put it in the background for running.

The SID (Session ID) column of the ps (1) command is the Session ID of the program running.

The process first appeared, and later people found that the process can be split into multiple small tasks for separate execution, so the concept of thread emerged. This will be discussed in detail in the subsequent thread sections.

Now the process has degraded to a container, and its existence is to carry the thread. PID seems to be a process number, which is actually consumed by the thread.

Processes and threads are just our saying. We can only see threads in the kernel. The so-called process management in the kernel is actually thread management, and the kernel will always execute tasks in thread units.

 

To sum up, sessions are used to carry Process Groups, Process Groups are used to carry processes, and processes are used to carry threads.

 

Chapter 9 is about to understand these concepts. Do you still remember the myshell we mentioned earlier, using fork (2) + exec (3) + wait (2) to implement a shell that can execute External commands. If you want to implement a shell that supports internal commands, you can take a closer look at Chapter 9. The main points of shell internal command processing are in Chapter 9. We won't discuss the ninth chapter in detail here. Interested friends can read the book by themselves. If you have any questions, you can join the discussion on the list of emails marked above the blog.

4. setsid (2)

1 setsid - create session and set process group ID2 3 #include <unistd.h>4 5 pid_t setsid(void);

Create a session and set the ID of the Process Group. This function is the most valuable function in Chapter 9th. Without this function, we will not be able to create a daemon later.

The caller cannot be a process group leader. After a call, the caller automatically becomes a new process group leader and disconnects from the control terminal. The process ID is set as the process group ID and session ID, therefore, the daemon generally has the same PID, PGID, and SID. The common usage is that the parent process fork (2) is a sub-process, and then the sub-process calls setsid (2) to turn itself into a daemon process, and the parent process exits.

 

5. Daemon

I will not write the chestnuts of the daemon, because the P375 Figure 13-1, the third edition of APUE, already has detailed code. I will summarize the chestnuts in the book.

Daemon features:

1) disconnects from the control terminal. ps (1) axj tty is a question mark (?).

2) It is the leader of the process group, that is, the same PID and PGID.

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

4) A new session is created, which is the leader of the session, so the PID is the same as the SID.

Run the ps (1) axj command to check whether the processes with the same PID, PGID, and SID are daemon processes.

The daemon can also use standard output, but it does not conform to common sense. Because the daemon has no control terminal, the daemon usually closes or redirects the standard input/output stream.

When writing a daemon, we will switch the working path to a certain existing path, such /. If your daemon is started on an detachable device (such as a USB flash drive), the device cannot be detached without changing the working path.

Umask (2) is called to set the file mode Creation mask to a known value, because the inherited mask may be set to deny some permissions, if the daemon requires these permissions, set them.

For the chestnuts in the book, there are two points to vomit:

1) The SIGHUP signal is used to notify the service process of soft restart. For example, after modifying the configuration file of a service, you can send a SIGHUP signal to the service process to re-read the configuration file, therefore, you do not need to ignore this signal unless otherwise specified.

2) if there are no special requirements, you do not have to disable all file descriptors. You only need to disable standard input, standard output, and labeling errors.

 

6. System Logs

The daemon should not use standard output. What if the daemon needs to record some events or errors? Then we need to use system logs.

System logs are generally stored in the/var/log/directory, but the permissions of log files under this directory are almost only for root users to read and write. How do common users write logs? This requires the use of system log functions to write logs.

The root user authorizes the syslogd service to write logs, and other programs need to call the syslogd service through a series of encapsulated functions to record logs. This improves log security and prevents unauthorized tampering of log files.

1 closelog, openlog, syslog - send messages to the system logger2 3 #include <syslog.h>4 5 void openlog(const char *ident, int option, int facility);6 void syslog(int priority, const char *format, ...);7 void closelog(void);

The openlog (3) function does not open a log file, but establishes a link with the syslogd service, indicating that the current process needs to write logs.

Parameter List:

Ident: indicates your identity, which is specified by the programmer. You can write anything.

Option: What content is to be appended to the log, multiple options are added by bit or link. LOG_PID is the append PID, which is the most commonly used.

Facility: message source. You can only specify one.

Message Source Description
LOG_CRON Message from scheduled task
LOG_DAEMON Message from daemon
LOG_FTP Message from FTP service
LOG_KERN Message from Kernel
LOG_USER By default, regular user-level messages

Table 1 common requirements for facility parameters

The syslog (3) function is used to submit log content. The parameter list is as follows:

Priority: priority. See the table below:

Level Description
LOG_EMERG "Severe" causes system unavailability
LOG_ALERT "Severe" must be handled 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

Take LOG_ERR as the demarcation line. If the program cannot continue running, report the level above LOG_ERR (including LOG_ERR ).

If the problem does not affect the program to continue running, report the level below LOG_ERR.

Too many logs must have high requirements on disk space, and too many useless logs will affect log auditing. Which levels of logs are configured in the configuration file are recorded in the log file. By default, logs of LOG_DEBUG and above are recorded.

Format: A formatted string similar to the printf (3) function. Do not use the Escape Character \ n. Otherwise, the log records a string "\ n" instead of a line break.

...: The placeholder parameter in format.

Closelog (3) indicates that log writing has ended.

 

7. single-instance daemon

Some Daemon must run only one instance at a time. They are called single-instance daemon. At startup, they will create a process lock file under/var/run. When the daemon starts, they will first determine whether the lock file exists. if it already exists, an error will be reported and the system will exit, if it does not exist, continue running and create a lock file, and delete it when exiting.

If you want the daemon to start automatically, you can configure it in the Automatic startup script:/etc/rc. d/rc. local.

 

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.