Process related -- daemon

Linux process related - Daemons

Related concepts

Process group

Concepts and characteristics

Process groups, also known as jobs. BSD is a new feature added to Unix around 1980. Represents a collection of one or more processes. Each process belongs to a process group. It is commonly used in the parameters of waitpid function and kill function. The concept of process group in operating system design is to simplify the management of multiple processes.

When the parent process creates a child process, the child process and the parent process belong to the same process group by default. Process group id = = first process 1 (leader process). Therefore, the team leader process ID: its process group id = = its process ID

kill -SIGKILL - process group ID (negative) can be used to kill all processes in the whole process group.

The leader process can create a process group, create the processes in the process group, and then terminate. As long as there is a process in the process group, the process group exists, which has nothing to do with whether the process leader terminates or not.

Process group lifetime: a process group is created until the last process leaves (terminates or transfers to another process group).
A process can set the process group ID for itself or its child processes

conversation

Create session

To create a session, you need to pay attention to the following 5 points:

  1. The calling process cannot be the process group leader. The process becomes a new session header
  2. The process becomes the leader of a new process group
  3. The new session discards the original control terminal, and the session has no control terminal
  4. If the calling process is a long i process, an error is returned
  5. When establishing a new session, first call fork, the parent process terminates, and the child process calls setsid

gitsid function

Gets the ID of the session to which the process belongs

pid_t getsid(pid_t pid); Successfully return the session ID of the process; Failure: - 1, setting error

A pid of 0 indicates to view the current session ID of the process

ps ajx command to view the processes in the system. Parameter a indicates that not only the processes of the current user but also the processes of all other users are listed, parameter x indicates that not only the processes with control terminals but also all processes without control terminals are listed, and parameter j indicates that the information related to job control is listed.

setsid function

#include <unistd.h>

pid_t setsid(void);

Successfully returned the session ID, failed to repent - 1;

Daemon

Daemon process is a background service process in Linux. It is usually independent of the control terminal and periodically performs some tasks or waits for some events. Names ending in d are generally used.

Some system service processes in the Linux background have no control terminal and cannot interact directly with users. It is not affected by user login and logout. It is running all the time. They are all daemons. For example, the implementation of read ahead and slow output mechanism; ftp server; nfs, server, etc.

The most critical step in creating a daemon is to call the setsid number to create a new Session and become SessionLeadier

Create daemon model

  1. Create a child process and the parent process exits

    All work is carried out in the subprocess, and the situation is separated from the control terminal

  2. Create a new session in the child process

    setsid() function

  3. Change the current directory to the root directory - not required

    chdir() function

    Prevent occupation of dismountable file systems

    You can change to another path

  4. Reset file permission mask

    umask() function

    Prevent inherited files from creating mask words and deny certain permissions

    Increase the flexibility of Daemons

  5. Close file descriptor 0 1 2

    The inherited open file will not be used, which wastes system resources and cannot be unloaded

  6. Start performing the core work of the daemon

  7. Daemon exit handler model

Daemon example

Create a daemon: create a file program name. Timestamp in $HOME/log / every minute

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


#define _FILE_NAME_FORMAT_ "%s/log/mydaemon.%ld" / / define file format

// Create files in the home directory / log every 1 minute
void catch_sig_touchfile(int num)
{
    char *HomeDir = getenv("HOME");
    char strFileName[256] = {0};
    sprintf(strFileName,_FILE_NAME_FORMAT_,HomeDir,time(NULL));
    int fd = open(strFileName, O_RDWR|O_CREAT,0666);
    // printf("%s\n",strFileName);
    if(fd < 0){
        perror("open err");
        exit(1);
    }
    close(fd);
}

int main()
{
    // 1. Create a child process and the parent process exits
    pid_t pid =fork();
    if(pid > 0){
        exit(0);
    }
    
    // 2. Be president
    setsid();
    
    // 3. Set mask
    umask(0);   // Give full permission
    
    // 4. Switch directories
    chdir(getenv("HOME"));  // Switch to home directory
    
    // 5. Close the file descriptor
    close(0);close(1);close(2);
    
    // 6. Implement core logic
    struct itimerval myit = {{60,0},{1,0}};
    setitimer(ITIMER_REAL,&myit,NULL);
    struct sigaction act;
    act.sa_flags = 0;
    sigemptyset(&act.sa_mask);
    act.sa_handler = catch_sig_touchfile;

    sigaction(SIGALRM,&act,NULL);
    while(1)
    {
        sleep(1);
    }
    // 7. Exit 

    return 0;
}

Note that after executing ps aux, check the process number kill -9 process number kill the process

Ordinary executable file making daemon

a.out is an executable file and can be replaced by your own

Execute the command: nohup. / a.out & if there is output, it will be output to nohup.out by default

You can also: nohup. / a.out > > a.txt & redirect the output

Tags: Linux

Posted on Sat, 18 Sep 2021 19:34:33 -0400 by KFredje