Orange Pi Zero2–Linux hot-swappable Udev mechanism

Directory

Introduction

daemon process

Daemon development mode

daemon application

douyinUtils.c Identify whether the douyin program exits

shouhu.c Do not execute the program in the daemon process until the program exits, that is, restart the douyin program

Set boot

Udev configuration file

?udev rule’s match key

Automatically mount U disk

ntfs format usb mount


Udev Introduction

udev is a device management tool,
udev
by
Daemon
run in the form of listening to the kernel
uevent
to manage /dev
Device files in the directory.
udev
Runs in user space, not kernel space. It can dynamically update device files according to the status of hardware devices in the system, including the creation and deletion of device files. Device files are usually placed in /dev
Under contents. use udev
after
/dev
The directory only contains devices that actually exist in the system.

Daemon process

Linux Daemon (daemon process) is a special process running in the background. It is independent of the controlling terminal and periodically performs some task or waits for some event to occur. It runs without user input and provides a service, either to the system as a whole or to a user program. Linux
Most servers of the system are implemented through daemon processes. Common daemons include the syslog process syslogd
,
web
server
httpd
, mail service
sendmail
and database server mysqld etc. The daemon’s name usually starts with
d
end

The UDEV daemon process can dynamically update device files according to the status of hardware devices in the system, including the creation and deletion of device files.

Basic Features:

  • long life cycle
    [
    not necessary
    ]
    Generally, it starts when the operating system starts, and closes when it is closed.

  • The daemon process is not associated with the terminal, that is, they do not have a control terminal, so when the control terminal exits, it will not cause the daemon process to exit

  • The daemon process runs in the background and does not occupy the terminal. The terminal can execute other commands

  • A daemon’s parent process is init
    process because its real parent process is in
    fork
    After the child process is produced, it precedes the child process
    exit
    exited, so it is a by init
    inherited orphan process

  • The Linux operating system itself has many daemon processes running silently, maintaining the daily activities of the system. perhaps
    30-50
    indivual

Enter the command to view the daemon process

ps -efj

The above operation analysis:

  • ppid = 0
    : Kernel process, which starts with the system startup, and its life cycle runs through the entire system.

  • cmd column name with
    []
    This is called the kernel daemon

  • ancestor init
    : It is also a system daemon process, which is responsible for starting the specific system services of each operating level; so many processes
    PPID
    yes
    init
    , which is also responsible for the adoption orphan process.

  • The name in the cmd column does not have
    []
    Ordinary daemons (userset daemons)

Daemon development mode

Complete directly with the daemon() function

Linux daemon process_linux daemon process_programming bird’s blog-CSDN blog

Linux: daemon process_linux daemon program_He Xiaoqi (qi)~’s blog

#include <unistd.h>
int daemon(int nochdir, int noclose);
Function parameters:
nochdir: When it is 0, it means change the current directory to "/"
noclose: When it is 0, it means that standard input, standard output, and standard error are redirected to "/dev/null"
return value:
Returns 0 on success, -1 on failure

timeDaemon.c

#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <time.h>
#include <stdio.h>
//C library function char *asctime(const struct tm *timeptr) returns a pointer to a string, which represents the date and time of the structure struct timeptr.
//The C library function struct tm *localtime(const time_t *timer) fills the tm structure with the value of timer. The value of timer is broken into a tm structure and represented in the local time zone.
/*
struct tm {
int tm_sec; seconds, range from 0 to 59
int tm_min; minute, range from 0 to 59
int tm_hour; hour, range from 0 to 23
int tm_mday; day of the month, range from 1 to 31
int tm_mon; month, range from 0 to 11
int tm_year; year since 1900
int tm_wday; day of the week, ranges from 0 to 6
int tm_yday; day of the year, ranges from 0 to 365
int tm_isdst; daylight saving time
};
*/
static bool flag = true;
void handler(int sig)
{
printf("I got a signal %d\
I'm quitting.\
", sig);
flag = false;
}
int main()
{
time_t t;
int fd;
//Create daemon process
if(-1 == daemon(0, 0))
{
printf("daemon error\
");
exit(1);
}
//Set signal handler function
struct sigaction act;
//Configure signaction parameters
act.sa_handler = handler;
sigemptyset( &act.sa_mask);
act.sa_flags = 0;
//Identify SIGQUIT and call the handler function
if(sigaction(SIGQUIT, & act, NULL))
{
printf("sigaction error.\
");
exit(0);
}
//Process work content
while(flag)
{
fd = open("/home/orangepi/daemon.log", O_WRONLY | O_CREAT | O_APPEND,0644);
if(fd == -1)
{
printf("open error\
");
}
t = time(0);
char *buf = asctime(localtime( &t));
write(fd, buf, strlen(buf));
close(fd);
sleep(10);
}
return 0;
}

kill daemon

Start the daemon at boot

sudo vi /etc/rc.local starts automatically at boot, absolute path plus program name

Add timeDaemon running program path in /etc/rc/local

sudo reboot to check if the daemon starts automatically

Daemon Application

Requirement: The program that requires the voice to swipe the phone is kept running to prevent the accidental crash of the application

Write a program to determine whether a process is running and whether it has exited:

douyinUtils.c Identify whether the douyin program exits

#include <stdio.h>
#include <string.h>


int main(){
    char buffer[128]={'\0'};
    FILE *file;
    char *cmd="ps -ef|grep douyin|grep -v grep";
    file=popen(cmd,"r");

    fgets(buffer,128,file);

    if(strstr(buffer,"douyin")!=NULL){
        printf("douyinUtils is running\
");
        printf("buffer:%s\
",buffer);
    }else{
        printf("douyinUtils is not running\
");
         printf("buffer:%s\
",buffer);

    }
    return 0;
}

Run tests

shouhu.c Do not execute the program in the daemon process until the program exits, that is, restart douyin program

#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <time.h>
#include <stdio.h>
#include <stdbool.h>
static bool flag = true;

int judMent(){
     char buffer[128]={'\0'};
    FILE *file;
    char *cmd="ps -ef|grep douyinUtils|grep -v grep";
    file=popen(cmd,"r");

    fgets(buffer,128,file);

    if(strstr(buffer,"douyinUtils")!=NULL){
       // printf("douyinUtils is running\
");

        printf("buffer:%s\
",buffer);
        return 0;
    }else{
        //printf("douyinUtils is not running\
");
         printf("buffer:%s\
",buffer);
        return -1;
    }

}

void handler(int sig)
{
    printf("I got a signal %d\
I'm quitting.\
", sig);
    flag = false;
}
int main()
{
    time_t t;
    int fd;
    //Create daemon process
    if(-1 == daemon(0, 0))
    {
        printf("daemon error\
");
        exit(1);
    }
    //Set signal handler function
    struct sigaction act;
    //Configure signaction parameters
    act.sa_handler = handler;
    sigemptyset( &act.sa_mask);
    act.sa_flags = 0;
    //Identify SIGQUIT and call the handler function
    if(sigaction(SIGQUIT, & act, NULL))
    {
        printf("sigaction error.\
");
        exit(0);
    }
    //Process work content
    while(flag)
    {
        if(judMent()==-1){
            system("/home/orangepi/douyin/douyinUtils /dev/ttyS5 & amp;");
        }
        sleep(2);
    }
    return 0;
}

Kill the Douyin program to see if the daemon will restart the Douyin program.

The daemon does not let the control program exit the instance:

two functions

  • One is to identify whether the douyin program exits
  • One is to execute the program in the daemon process after recognizing that the program exits, that is, to restart the douyin program

Set boot startup

sudo vi /etc/rc.local

/home/orangepi/douyin/douyinUtils /dev/ttyS5 &

/home/orangepi/douyin/shouhuDouyin



exit 0

Udev configuration file

The rule file is the most important part in udev, and it is stored under /etc/udev/rule.d/ by default. All rule files must have a “.rules” extension.

Here’s a simple rule:

KERNEL=="sda", NAME="my_root_disk", MODE="0660"

KERNEL is the match key, and NAME and MODE are the assignment keys. The meaning of this rule is: if there is a device whose kernel name is sda, this condition will take effect, and the following assignment will be executed: create a device file named my_root_disk under /dev, and set the permission of the device file to 0660.

udevadm info –attribute-walk –name=/dev/
device name

udevMatch keys for rules

action
:event(
uevent
) behavior, for example:
add
(add device),
remove
(delete device);

KERNEL
: Kernel device name, for example:
sda
,
cdrom
;

DEVPATH
:equipment
devpath
path;

SUBSYSTEM
: The subsystem name of the device, for example:
sda
The system is
block
;

BUS
: The device is in
devpath
in the bus name, for example:
USB
;

DRIVER
: The device is in
devpath
device driver name, for example:
ide-cdrom
;

ID
: The device is in
devpath
in the identification number;

SYSFS{filename}
:equipment
devpath
Under the path, the property file of the device
“filename”
the contents of

ENV{key}
: environment variable. In one rule, you can set up to five matching keys of environment variables;

PROGRAM
: call an external command;

RESULT
: external command
PROGRAM
The returned result.

Automatically mountUDisk

ACTION=="add", SUBSYSTEMS=="usb", SUBSYSTEM=="block", RUN{program} + ="/bin/mkdir
/media/%k" ,RUN{program} +="/usr/bin/systemd-mount --no-block --collect $devnode
/media/%k"

ntfs format usb compatible solution:

Download and install the tree, view the file

sudo apt-get install tree

Use tree /media to view the usb file and realize the mount.

syntaxbug.com © 2021 All Rights Reserved.