Linux - process and scheduled task management

1, Relationship between program and process

◾ program

  • Executable code and data stored in hard disk, optical disk and other media
  • Statically saved code in file

◾ process

  • Program code running in CPU and memory
  • Dynamically executed code
  • Parent and child processes
    • Each program can create one or more processes

1. Process, program and thread

  • Program: executable code and data stored in hard disk, optical disk and other media, which can contain one or more processes
  • Process: the program code running in CPU and memory, dynamically executed code, and the process can contain one or more threads and one or more sub processes
  • Thread: the smallest unit that performs an operation

2. Five states of the process

  1. Running status (running or waiting in the run queue)
  2. Interrupt (in sleep, blocked, waiting for the formation of a condition or receiving a signal)
  3. Non interruptible (the process cannot wake up and run after receiving the signal, and the process must wait until an interrupt occurs)
  4. Dead (the process is terminated, but the process descriptor exists until it is released after the parent process calls wait4() system call)
  5. Stop (the process stops running after receiving sigstop, sigstp, sigtin and sigtou signals)

2, View process information ps (static)

View static process statistics

Method 1:

[root@localhost ~]# ps aux
a:Displays all processes on the terminal, including those of other users.
u:Represents the user who listed the process.
x:Displays the processes of all terminals.

USER∶ User of the process.
PID∶Process ID. 
%CPU∶Process occupied CPU percentage.
%MEM∶ Percentage of memory used.
VSZ∶The amount of virtual memory used by the process( KB). 
RSS∶ The amount of physical memory occupied by the process( KB). 
TTY∶ The name of the terminal that started the process. Processes that are not started from the terminal are displayed as ?
STAT∶Status of the trip
 First column: (the first status is capitalized)
D: Non interruptible
S: Interruptible
r: normal operation
z: Dead state
T: Stop operation
 Second column:
<: High priority (available) cpu (longer slice)
+: The current process is running in the foreground
N: Low priority
s: Control process
l: Is multithreaded
START∶The time when the process was triggered to start.
TTME∶The process is actually used CPU Run time.
COMMAND∶Start command of the process.

Method 2:

[root@localhost ~]# ps -<elf
●-e: Display all process information in the system.
●-l: Displays process information in long format.
●-f: Display process information in a complete format.

F∶ The system token assigned by the kernel to the process.
S∶ Status of the process.
UID∶ The user who started these processes.
PID∶ Process of process ID. 
PPID∶ The process number of the parent process (if the process was started by another process).
C∶ In the process life cycle CPU Utilization.
PRI∶ The priority of the process (the higher the number, the lower the priority).
NI∶ The humility value is used to participate in determining priorities.
ADDR∶ Memory address of the process.
Sz∶ If the process is swapped out, the approximate size of the swap space required.
WCHAN∶If the process is sleeping, the system function name in sleep is displayed.
STIME∶ The system time when the process started.
TTY∶ The terminal device when the process starts.
TIME∶ Cumulative time required to run the process CPU Time.
CMD∶ Start command of the process.

View process information top (dynamic)

Information corresponding to each line

top - 12:56:51 up 2:50, 2 users, load average: 0.00, 0.01, 0.05

#The first line is the task queue information
12:56:51: system time
up 2:50: System run time
2 user: Number of currently logged in users
load average: 0.00, 0.01, 0.05 :System load, that is, the number of tasks processed by the system in unit time,
The last three values are the average values from 1 minute, 5 minutes and 15 minutes ago to now

Tasks: 223 total, 1 running, 222 sleeping, 0 stopped, 0 zombie

Second behavior process information
Tasks : Total processes
running : Number of running processes
sleeping : Number of dormant processes
stopped : Number of aborted processes
zombie : Number of dead processes

%Cpu(s): 0.0 us, 0.1 sy, 0.0 ni, 99.9 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st

Third behavior CPU Information
us : User occupancy
sy : Kernel occupancy
ni : Priority scheduling occupancy
id : free CPU,To understand the free CPU Percentage, mainly depends on%id part
wa: I/O Waiting for occupation
hi : Hardware interrupt occupation
si : Software interrupt occupation
st : Virtualization occupancy

KiB Mem : 3861520 total, 1190856 free, 773196 used, 1897468 buff/cache

The fourth line is memory information
total: Total memory space
free : idle memory
used: Used memory
buff/cache: The sum of physical memory and swap memory buffers

KiB Swap: 4064252 total, 4064252 free, 0 used. 2730428 avail Mem

Fifth, spatial information exchange
total: Total switching space
free : Free swap space
used: Used swap space
avail Mem: Available physical space

Explanation of columns in process information area

PID: process id
USER: User name of the process owner
PR: priority
NI: Humility value. Negative values indicate high priority and positive values indicate low priority
VIRT: Total amount of virtual memory used by the process, in kb
RES: Size of physical memory used by the process, in kb
SHR: Shared memory size in kb
S: Process status
%CPU: From last update to now CPU Time occupancy percentage
%MEM: Percentage of physical memory used by the process
TIME+: Used by the process CPU Total time, unit 1/100 second
COMMAND : Command name/command line

top common commands

Shortcut keymeaning
P KeySort by CPU usage percentage size
M keySort by resident memory size
N keySort by start time
c keyToggles the display of the command name and the full command line
h keyYou can get the online help information of the top program
k keyEnter the PID number of the specified process according to the prompt and press enter to terminate the corresponding process
q keyExit top program
Number 1 keyDisplays the number and status of CPU s

pgrep command -- view process information

pgrep: Query process according to specific conditions PID information
 Example: pgrep -l "log"
    pgrep -l -U teacher -t tty2
-l: Display the process name. By default, only the process name is output PID number
-U: Specify a specific user
-t: Designated terminal

pstree command - view process tree

List process information in a tree structure
pstree -aup
-a: Display complete information
-u: List corresponding user names
-p: List corresponding PID number
 Example: pstree -ap teacher: View only the process tree structure belonging to the specified user

Start mode of process

1. Start the process manually

Foreground start∶ The user enters the command and executes the program directly
 Background start∶Add at the end of the command line"&"Symbol
[root@localhost~]#cp /dev/cdrom mycd.iso &
[1] 28454 (The output information includes background task serial number PID No.)

2. Dispatch start

use at Command to set a one-time scheduled task
 use crontab Command to set periodic scheduled tasks

3. Front and back scheduling of process

①Ctrl+z Combination key
 Suspend the current program, that is, transfer to the background and stop execution
②jobs command
jobs [-l]
View the list of tasks in the background
③fg command
 To restore the background process to the foreground, you can specify the task sequence number

4. Terminate the operation of the process

When the user executes a process in the foreground, you can press Ctrl+C to forcibly interrupt (such as when the command does not respond for a long time). After interrupting the operation of the foreground process, the system will return to the command line prompt state and wait for the user to enter a new command. When pressing Ctrl+C cannot terminate the program or needs to end the process running on other terminals or in the background, you can use the special process termination tools kill, kill and pkill.

(1) Use the kill command to terminate the process
When terminating a process through the Kill Command, you need to use the PID number of the process as a parameter. When there is no specific option, the Kill Command will send a termination signal to the process and exit the operation normally. If the process has been unable to respond to the termination signal, the process can be forcibly terminated in combination with the "- 9" option. Forced termination of the process may result in the loss of some data during program operation. Therefore, do not easily use the "- 9" option when you have to. For example, if the PID number of the sshd process of the SSH service is 2869, the process sshd can be terminated after executing the "kill 2869" command.

[root@localhost~]#pgrep-1"sshd" / / query the PID number of the target process
 2869 sshd
[root@localhost~]#kill 2869 / / terminate the process with the specified PID
[root@localhost ~]# pgrep -l "sshd" / / confirm that the process has been terminated (no result in query)

For system processes that cannot be terminated normally, if necessary, they can be forcibly terminated in combination with the "- 9" option. For example, the following operation shows the process of forcibly terminating the vim process.

[root@localhost~]# vim tmpfile / / open the vim program and suspend it as a test
[1]+Stopped          vim tmpfile
[root@localhost~]#jobs-1 / / query the PID number of the target process
[1]+2993 stop it vim tmpfile
[root@localhost~]#kill 2993 / / try to end the process normally
[root@localhost~]#jobs-1 / / it is found that the vim process does not exit
[1]+2993 stop it vim tmpfile
[root@localhost~]# kill-9 2993 / / forcibly terminate the target process
[root@localhost~]#jobs-l / / the vim process is terminated successfully
[1]+2993 Killed
 vim tmpfile

(2) Use the kill command to terminate the process
Using the kill command can terminate the process by the process name. When it is necessary to end multiple processes with the same name in the system, using the Kill Command will be more convenient and efficient. The kill command also has a "- 9" option. For example, executing the "kill-9 VIM" command can forcibly terminate all processes named vim.

[root@localhost~]# vim testfile1 / / suspend the first vim test process
[1]+ Stopped
 vim testfilel
[root@localhost~]# vim testfile2 / / suspend the second vim test process
[2]+Stopped
 vim testfile2
[root@localhost~]#jobs-1 / / confirm the information of the process to be terminated
[1]-3029 stop it
 vim testfilel
[2]+3030 stop it
 vim testfile2
[root@localhost~]#Kill-9 VIM / / terminate multiple processes by process name
[1]-Killed
 vim testfilel
[2]+Killed vim testfile2

(3) Use the pkill command to terminate the process
Using pkill command, a specific process can be terminated according to the name of the process, the user running the process, the terminal where the process is located and other attributes. Most options are basically similar to pgrep command, such as "- U" (specified user), "- t" (specified terminal) and other options, which are very convenient to use. For example, to terminate a process started by user hackli, including logging into the shell, you can do the following.

[root@localhost~]#pgrep-1-U "hackli" / / confirm the information about the target process
 3045 bash
[root@localhost ~]# pkill-9-U "hackli" / / forcibly terminate the user's hackli process
[root@localhost~]# pgrep-1-U "hackli" / / confirm that the target process has been terminated

5. Planned task management

1.at one time task setting

at [HH:MM] [yyyy-mm-dd]
Ctrl+D submit task
atq view the list of unexecuted tasks
atrm 1 delete task 1

For example, the following operations first confirm the current system time through the date command and set it to May 5, 2016
At 14:55 on the day, the following tasks are automatically executed: count the number of processes run by root in the system at this time point,
And save the value to the "/ tmp/ps.root" file.

[root@kgc~]# date
 2016 Thursday, May 5, 2014:45:05 CST
[root@kgc~]# at 14:55 2016-05-05
 at>pgrep-U root|wc-1>/tmp/ps.root
 at><EOT>                           //After setting the task, press Ctrl+D to submit
 job 1 at 2016-05-05 14:55
[root@kgc~]#cat/tmp/ps.root / / verify the command result after the scheduled time expires
 63

The following operations will set a scheduled task and automatically shut down the current system at 21:30 of the day.

[root@kgc~]# at 21:30
 at>shutdown-h now
 at><EOT>
 job 2 at 2016-05-05 21:30

For scheduled tasks that have been set but have not yet been executed (before the time point), you can query through the atq command.
However, the at tasks that have been executed will no longer appear in the list.

[root@kgc~]#atq
 2    2016-05-05 21:30 a root

To delete the at task with the specified number, you can use the atrm command. The deleted at task will not be executed,
And it will not be displayed in the display result of atq command. However, tasks that have been executed cannot be deleted.

[root@kgc~]#atrm 2 / / delete the second at scheduled task
[root@kgc~]#atq / / confirm that task 2 has been deleted

2. crontab periodic planning tasks

  • Repeat the command operation specified by the user according to the preset time period (minute, hour, day, month, week)
  • It is a periodic scheduled task
  • Main setting file:
    Global configuration file, located in file: / etc/crontab
    The default setting of the system is located in the directory: / etc/cron*/
    User defined settings in the file: / var/spool/cron / username

See: / etc/crontab for the contents of the global configuration file

[root@kgc ~]# cat /etc/crontab
 SHELL=/bin/bash                           //Set the Shell environment for executing scheduled tasks
 PATH=/sbin:/bin:/usr/sbin:/usr/bin        //Define the path of executable commands and programs
 MAILTO=root                               //Send the task output information to the mailbox of the specified user
 HOME=/                                    //Home directory to use when performing scheduled tasks
 # For details see man 4 crontabs
 # Example of job definition:
 # .----------------minute (0-59)
 # | .-------------hour (0 -23)
 # | | .---------- day of month(1-31)
 # | | |.-------month(1- 12) OR jan,feb,mar,apr ...
 # | | | | .---- day of week (0 - 6)(Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
 # | | | | |
 # * * * * * user-name command to be executed

Common options

  • Edit scheduled task
    Crontab -e [- u user name] - u defaults to the current user
  • View scheduled tasks
    crontab -I [- u user name]
  • Delete scheduled task
    crontab -r [- u user name]

Format of crontab task configuration


◾ Special representation of time value

  • ***Indicates any time within the range
  • , representing multiple discontinuous time points of the interval
  • -Represents a continuous time range
  • / specify the time and frequency of the interval

◾ Application example

0 17 * *1-5           17 every day from Monday to Friday:00
30 8 * *1,3,5         Every Monday, Wednesday and Friday at 8:30
0 8-18/2 * * *        8 Every 2 hours between 00:00 and 18:00
0 * * /3 * *          Every 3 days

Added by telefiend on Thu, 10 Feb 2022 02:56:51 +0200