[Linux] Daemon process (with introduction to terminals, process groups, and sessions)

orange color

1. Terminal

echo $$ 

You can view the ID of the current terminal process
Insert image description here

  • By default (without redirection), the standard input, standard output and standard error output of each process are directed to the control terminal. The process reads from the standard input, that is, reads the user's keyboard input, and the process writes to the standard output or standard error output. It is output to the monitor.

2. Process group

  • Process groups and sessions form a two-level hierarchical relationship between processes: a process group is a collection of related processes. A session is a collection of related process groups. Process composition session is an abstract concept defined to support shell job control. Users can interactively run commands in the foreground or background through the shell.
  • A process group consists of one or more processes that share the same process group identifier (PGID). A process group has a process group leader process, which is the process that created the group. Its process ID is the ID of the process group. The new process will inherit the process group ID to which its parent process belongs.
  • A process group has a life cycle. The start time is the time when the first process creates the group, and the end time is the time when the last member process exits the group. A process may exit the process group by terminating. It is also possible to exit a process group because it joins another process group. The leader process of a process group does not need to be the last member to leave the process group.

3. Conversation

  • A session is a collection of process groups. The session first process is the process that creates the new session, and its process ID becomes the session ID. The new process inherits the session ID of its parent process.
  • 一个会话中的所有进程共享单个控制终端。The controlling terminal is created when the session leader opens a terminal device for the first time. A terminal may be the controlling terminal for at most one session.
  • At any time, one of the process groups in the session will become the terminal's foreground process group, and the other process groups will become the background process group. Only processes in the foreground process group can read input from the controlling terminal. When the user enters terminal characters in the control terminal to generate a signal, the signal will be sent to all members of the foreground process group.
  • When the connection to the controlling terminal is established, the session head process becomes the controlling process of the terminal.

4. Daemon process

  • Daemon Process, also known as Daemon process (elf process), is the background server in Linux. It is a long-lived process that is usually independent of the controlling terminal and periodically performs some task or waits for some event to occur. Generally, names ending in d are used.
  • The daemon process has the following characteristics: 1. The life cycle is very long. The daemon process will be created when the system starts and will run until the system is shut down. 2. It runs in the background and does not have a control terminal. The absence of a control terminal ensures that the kernel will never automatically generate any control signals and terminal-related signals (such as SIGINT, SIGQUIT) for the daemon.

Daemon creation steps:

  • Execute a fork(), then the parent process exits and the child process continues execution
  • The child process calls setsid() to open a new session
  • Clear the process's umask to ensure that the daemon has the required permissions when it creates files and directories
  • Modify the current working directory of the process, usually to the root directory (/).
  • Closes all open file descriptors that the daemon inherited from its parent process.
  • After closing file descriptors 0, 1, and 2, the daemon typically opens /dev/null and uses dup2() to make all these descriptors point to this device.
  • Core business logic.

Code example:

/*
    写一个守护进程,每隔2s获取一下系统时间,将这个时间写入到磁盘文件中。
*/

#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/time.h>
#include <signal.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>

void work(int num) {
    
    
    // 捕捉到信号之后,获取系统时间,写入磁盘文件
    time_t tm = time(NULL);
    struct tm * loc = localtime(&tm);
    // char buf[1024];

    // sprintf(buf, "%d-%d-%d %d:%d:%d\n",loc->tm_year,loc->tm_mon
    // ,loc->tm_mday, loc->tm_hour, loc->tm_min, loc->tm_sec);

    // printf("%s\n", buf);

    char * str = asctime(loc);
    int fd = open("time.txt", O_RDWR | O_CREAT | O_APPEND, 0664);
    write(fd ,str, strlen(str));
    close(fd);
}

int main() {
    
    

    // 1.创建子进程,退出父进程
    pid_t pid = fork();

    if(pid > 0) {
    
    
        exit(0);
    }

    // 2.将子进程重新创建一个会话
    setsid();

    // 3.设置掩码
    umask(022);

    // 4.更改工作目录
    chdir("/root");

    // 5. 关闭、重定向文件描述符,先创建指向null的文件描述符fd,再把标准输入标准输出和标准错误重定向到null文件,
    //否则的话使用printf打印的信息会直接输出到终端。而重定向后就会输入到我定向的文件中
    int fd = open("/dev/null", O_RDWR);
    dup2(fd, STDIN_FILENO);
    dup2(fd, STDOUT_FILENO);
    dup2(fd, STDERR_FILENO);

    // 6.业务逻辑

    // 捕捉定时信号
    struct sigaction act;
    act.sa_flags = 0;
    act.sa_handler = work;
    sigemptyset(&act.sa_mask);
    sigaction(SIGALRM, &act, NULL);

    struct itimerval val;
    val.it_value.tv_sec = 2;
    val.it_value.tv_usec = 0;
    val.it_interval.tv_sec = 2;
    val.it_interval.tv_usec = 0;

    // 创建定时器
    setitimer(ITIMER_REAL, &val, NULL);

    // 不让进程结束
    while(1) {
    
    
        sleep(10);
    }

    return 0;
}

Compile and run the program
Insert image description here
Insert image description here
Insert image description here

Finally, you can see that a time.txt file was successfully created in the working directory I set (this working directory can be changed through the child in the program). Browsing through vim, you can see that the time is continuously written to the time.txt file.
Note: Use ps aux to find that ./daemon exists. This process is a daemon process and cannot be stopped through the control terminal. You can only force kill using kill -9 pid.

Guess you like

Origin blog.csdn.net/mhyasadj/article/details/130849274