CentOS 7 Process and Scheduled Task Management (Theory + Practice)

View and control processes

The relationship between programs and processes

  • program

    • Executable code and data stored on media such as hard disks, discs, etc.
    • Statically saved code
  • process
    • Program code running in CPU and memory
    • Code executed dynamically
    • Parent and Child Processes
    • Each process can create one or more processes

Simply put, a program is a collection of instructions that a computer can recognize to run.A process is a program being executed.A process is a part of a program that generates a process when it runs.

View process

Understanding the status of processes in the system is a prerequisite for managing processes. Different command tools can be used to view the status of processes from different perspectives.

  • ps command - view static process statistics

    • Command Format

    ps [Options]

    • Common Options

    a: Displays all process information under the current terminal, including processes of other users.

    u: Use a user-centric format to output process information.

    x: Displays the current user's process information under all terminals.

    -e: Displays all process information within the system.

    -l: Display process information in a long format.

    -f: Display process information in a complete format.

[root@localhost ~]# ps aux
USER        PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root          1  0.0  0.3 193700  6500 ?        Ss   14:05   0:06 /usr/lib/systemd/system
root          2  0.0  0.0      0     0 ?        S    14:05   0:00 [kthreadd]
root          3  0.0  0.0      0     0 ?        S    14:05   0:00 [ksoftirqd/0]
root          5  0.0  0.0      0     0 ?        S<   14:05   0:00 [kworker/0:0H]
root          7  0.0  0.0      0     0 ?        S    14:05   0:00 [migration/0]
root          8  0.0  0.0      0     0 ?        S    14:05   0:00 [rcu_bh]
root          9  0.0  0.0      0     0 ?        S    14:05   0:02 [rcu_sched]
root         10  0.0  0.0      0     0 ?        S    14:05   0:00 [watchdog/0]
...//Omit some content...

In the output information above, the first behavior list title has the following meanings for each field:

USER: Name of the user account that started the process.

PID: The digital ID number of the process in the system, which is unique in the current system.

%CPU: Percentage of CPU usage.

%MEM: Percentage of memory used.

VSZ: The amount of virtual memory (swap space) used.

RSS: The amount of resident memory (physical memory) used.

TTY: Indicates on which terminal the process is running."?" means unknown or does not require a terminal.

STAT: Displays the current state of a process, such as S (dormant), R (running), Z (dead), < (high priority), N (low priority), s (parent process), and + (foreground process).

START: The time the process was started.

TIME: The CPU time consumed by the process.

COMMAND: The name of the command that started the process.

[root@localhost ~]# ps -elf
F S UID         PID   PPID  C PRI  NI ADDR SZ WCHAN  STIME TTY          TIME CMD
4 S root          1      0  0  80   0 - 48425 ep_pol 14:05 ?        00:00:06 /usr/lib/systemd/systemd --switche
1 S root          2      0  0  80   0 -     0 kthrea 14:05 ?        00:00:00 [kthreadd]
1 S root          3      2  0  80   0 -     0 smpboo 14:05 ?        00:00:00 [ksoftirqd/0]
1 S root          5      2  0  60 -20 -     0 worker 14:05 ?        00:00:00 [kworker/0:0H]
1 S root          7      2  0 -40   - -     0 smpboo 14:05 ?        00:00:00 [migration/0]
1 S root          8      2  0  80   0 -     0 rcu_gp 14:05 ?        00:00:00 [rcu_bh]
1 S root          9      2  0  80   0 -     0 rcu_gp 14:05 ?        00:00:02 [rcu_sched]
5 S root         10      2  0 -40   - -     0 smpboo 14:05 ?        00:00:00 [watchdog/0]
5 S root         11      2  0 -40   - -     0 smpboo 14:05 ?        00:00:01 [watchdog/1]
...//Omit some content...

In the output information above, we can see that the ps-elf output is more comprehensive than the ps-elf output, and its list fields are also somewhat different, meaning the following:

UID: Same meaning as USER above.

PPID: The parent of the current process.

C: cpu usage.

PRI: Priority (user-state priority).

NI: The lower the kernel priority (-20~19) value, the higher the priority.

ADDR: Running state (-indicates running).

SZ: Indicates swap swap swap partition capacity is occupied.

WCHAN: Name of the current process kernel state

When the ps command is executed directly without any options, only processes opened in the current user session are displayed:

[root@localhost ~]# ps
   PID TTY          TIME CMD
  1624 pts/0    00:00:00 bash
 12076 pts/0    00:00:00 ps
  • top command - view process dynamics

    The ps command allows you to see static process information and does not provide continuous feedback on the running status of the current process.If you want to display the status information of each process in a dynamic refresh mode, you can use the top command.The top command will display the process rankings in the current terminal in a full-screen interactive interface, and keep track of system resource usage, including CPU, memory, etc. By default, it refreshes every three seconds, which is similar to the task manager in the Windows operating system.

Tasks: 145 total,   1 running, 144 sleeping,   0 stopped,   0 zombie
%Cpu(s):  0.0 us,  0.2 sy,  0.0 ni, 99.8 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
KiB Mem :  1867048 total,   478488 free,   339336 used,  1049224 buff/cache
KiB Swap:  4194300 total,  4193864 free,      436 used.  1294208 avail Mem 

   PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND             
   615 root      20   0  305296   6204   4820 S   0.3  0.3   0:13.89 vmtoolsd             
     1 root      20   0  193700   6500   3688 S   0.0  0.3   0:07.02 systemd             
     2 root      20   0       0      0      0 S   0.0  0.0   0:00.02 kthreadd             
     3 root      20   0       0      0      0 S   0.0  0.0   0:00.31 ksoftirqd/0        
     5 root       0 -20       0      0      0 S   0.0  0.0   0:00.00 kworker/0:0H         
     7 root      rt   0       0      0      0 S   0.0  0.0   0:00.11 migration/0         
     8 root      20   0       0      0      0 S   0.0  0.0   0:00.00 rcu_bh              
     9 root      20   0       0      0      0 S   0.0  0.0   0:02.43 rcu_sched           
    10 root      rt   0       0      0      0 S   0.0  0.0   0:00.12 watchdog/0       

In the above output information, the first part shows summary information such as system tasks (Tasks), CPU usage, memory usage (Mem), swap space (Swap), etc. The meanings of the information are as follows:

Tasks system task information: total: total number of processes; running: number of running processes; sleeping: number of dormant processes; stopped: number of processes aborted; zombie: number of processes that are dead and unresponsive

CPU usage information: us: user usage; sy: kernel usage; ni: priority scheduling usage; id: idle CPU, wa:I/O waiting usage; hi: hardware interrupt usage; si: software interrupt usage; st: virtualization usage

Mem memory usage information: total: total memory space; free: free memory; used: used memory; buff/cache: sum of buffers of physical memory and swap memory

Swap swap space usage: total: total swap space; free: free: free swap space; used: used swap space; avail Mem: available physical space.

In top command mode, the list can also be sorted by the c key according to CPU usage; "m key" by memory usage; "q key by exit mode"

  • pgrep command - query process information

    With the pgrep command, you can query by specifying only part of the process name

    • Common formats

    -l:[process name]

    -U [user name]

    -t [terminal]

[root@localhost ~]# pgrep -l "log"
291 xfs-log/sda2
[root@localhost ~]# pgrep -l -U root -t tty1
10050 X
  • pstree command - view process tree

    The pstree command outputs the tree structure of processes in the Linux operating system to make a more intuitive judgment of the relationships between processes (parent and child).

    • Common formats

    -a: Display complete information

    -u: corresponding user name at column

    -p: List corresponding PID numbers

[root@localhost ~]# pstree -aup
systemd,1 --switched-root --system --deserialize 21
  ├─ModemManager,575
  │   ├─{ModemManager},591
  │   └─{ModemManager},601
  ├─NetworkManager,669 --no-daemon
  │   ├─dhclient,793 -d -q -sf /usr/libexec/nm-dhcp-helper -pf /var/run/dhclient-ens33.pid -lf...
  │   ├─{NetworkManager},681
  │   └─{NetworkManager},685
  ├─VGAuthService,567 -s
  ├─abrt-watch-log,577 -F Backtrace /var/log/Xorg.0.log -- /usr/bin/abrt-dump-xorg -xD
  ├─abrt-watch-log,618 -F BUG: WARNING: at WARNING: CPU: INFO: possible recursive locking detectedernel BU
  ├─abrtd,569 -d -s
...//Omit some content...

You can also view only the process tree structure belonging to the specified user, as long as the user name is specified as a parameter.

[root@localhost ~]# pstree -ap sun
at-spi-bus-laun,12820
  ├─dbus-daemon,12825 --config-file=/usr/share/defaults/at-spi2/accessibility.conf --nofork ...
  │   └─{dbus-daemon},12826
  ├─{at-spi-bus-laun},12821
  ├─{at-spi-bus-laun},12822
  └─{at-spi-bus-laun},12824

at-spi2-registr,12828 --use-gnome-session
  ├─{at-spi2-registr},12831
  └─{at-spi2-registr},12832
...//Omit some content...

Control process

1. Start the process

On Linux operating systems, new processes can be started manually by users or scheduled to start on a scheduled schedule

  • Start the process manually
    • Foreground startup: user input command, execute program directly
    • Background startup: add the'&'symbol at the end of the command line
[root@localhost ~]# Cp/opt/data/Packages/ /mnt/ & //Copy the Packages directory to the MNT directory and run in the background
[1] 15054                    //Show background running file task number, PID number            
  • Schedule Start

    Set up one-time scheduled tasks using the at command

    Set up periodically scheduled tasks using the crontab command

2. Change the way processes run

  • Ctrl+Z key combination suspends the current process

    When a command in the Linux operating system is being executed in the foreground, pressing the Ctrl+Z key combination can bring the current command into the background and stop execution.

[root@localhost ~]# Cp-r/opt/data/Packages/ /mnt //Execute command to copy package file to MNT directory
^Z                                        //Press Ctrl+Z to move the task to background and stop it
[1]+  Stopped               cp -i -r /opt/data/Packages/ /mnt  //Task moved to background and stopped
[root@localhost ~]# 
  • jobs Command - View Background Processes

    When you need to view a process task running in the background in the current terminal, you can use the jobs command, combined with the'-l'option, to display the corresponding PID number of the process at the same time.

[root@localhost ~]# Jobs-l //View processes running in the background
[1]+ 15254 Stop it                  cp -i -r /opt/data/Packages/ /mnt   //Show background information
  • fg command - restore background processes to run

    Use the fg command to revert background tasks back to running in the foreground.Unless there is only one task in the background, the fg command needs to specify the task number of the background process as a parameter.

[root@localhost ~]# fg 1 //Modulate background tasks to run in the foreground
cp -i -r /opt/data/Packages/ /mnt      //Task returns to foreground to continue running
  • bg command - suspend tasks in the background and resume execution in the background

    With the bg command, tasks suspended in the background (such as hanging up by pressing the Ctrl+Z key) can be resumed and operations continue in the background. Unless there is only one task in the background, the bg command needs to specify the task number of the background process as a parameter.

[root@localhost ~]# Jobs-l //View background running processes
[1]+ 15254 Stop it                  cp -i -r /opt/data/Packages/ /mnt
[root@localhost ~]# bg 1 //Start programs that are paused in the background and execute in the background
[1]+ cp -i -r /opt/data/Packages/ /mnt &   //Start Task Execution
[root@localhost ~]# Jobs-l //View background running processes
[1]+ 15254 Running               cp -i -r /opt/data/Packages/ /mnt &  //Tasks continue to run in the background

3. Terminate process execution

  • kill Command - used to terminate a process with a specified PID number

    When terminating a process with the kill command, you need to use the PID number of the process as a parameter.When no specific option is available, the Kill Command sends a termination signal to the process and exits normally. If the process is no longer able to respond to the termination signal, the process can be forcibly terminated with the'-9'option.

[root@localhost ~]# Rm-rf/mnt/Packages/ //Remove Packages directory as file under MNT directory
[root@localhost ~]# Cp-r/opt/data/Packages/ /mnt & //Copy File Packages to the MNT directory and run in the background
[1] 15602
[root@localhost ~]# Jobs-l //View background running tasks and display the PID number
[1]+ 15602 Running               cp -i -r /opt/data/Packages/ /mnt &
[root@localhost ~]# kill 15602 //Terminate background running task with PID number 15602
[root@localhost ~]# jobs //view background tasks
[1]+  Terminated               cp -i -r /opt/data/Packages/ /mnt  //Task terminated
[root@localhost ~]# Rm-rf/mnt/Packages/ //Remove Packages directory as file under MNT directory
[root@localhost ~]# Cp-r/opt/data/Packages/ /mnt & //Copy File Packages to the MNT directory and run in the background
[1] 15754
[root@localhost ~]# Kill-9 15754 //Force stop of task with PID number 15754
[root@localhost ~]# Jobs-l //View background task information
[1]+ 15754 Killed               cp -i -r /opt/data/Packages/ /mnt   //Task Force Stop
  • killall command - used to terminate all processes with the specified name

    The killall command can be used to terminate a process by its name. It is more convenient and efficient to use the killall command when multiple processes with the same name need to be terminated in the system.The killall command also has the'-9'option.

[root@localhost ~]# Rm-rf/mnt/Packages/ //Delete Packages just copied from the MNT directory
[root@localhost ~]# Cp-r/opt/data/Packages/ /mnt & //Copy File Packages to the MNT directory and run in the background
[1] 15825
[root@localhost ~]# cp -r /opt/data/Packages/ /boot &
[2] 15827                                        //Copy file Packages to directory boot and run in the background
[root@localhost ~]# killall cp //stop all cp tasks
[1]-  Terminated               cp -i -r /opt/data/Packages/ /mnt
[2]+  Terminated               cp -i -r /opt/data/Packages/ /boot  //Stopped All
[root@localhost ~]# Vim/mnt/data1 & //edit file data1 and run in the background
[1] 16007
[root@localhost ~]# Vim/mnt/data2 & //edit file data2 and run in the background
[2] 16009

[1]+  Stopped               vim /mnt/data1
[root@localhost ~]# Jobs-l //View Background Shipping Tasks
[1]- 16007 Stop it (tty output)     vim /mnt/data1
[2]+ 16009 Stop it (tty output)     vim /mnt/data2
[root@localhost ~]# Killall-9 vim // end-of-enforcement daemon vim program
[1]-  Killed               vim /mnt/data1  
[2]+  Killed               vim /mnt/data2     //Forced Stop
  • pkill command - Terminates the corresponding process based on specific conditions

    The pkill command can terminate a specific process based on the name of the process, the user running the process, the terminal on which the process resides, and many other properties. Most options are similar to the pgrep command.

  • Common Options

    -U: Terminate the process based on the user name to which it belongs

    -t: Terminate the process based on its terminal

    -9: Force end of process (with -U command to force specified user to go offline)

[root@localhost ~]# who //view logged-in users
root     pts/0        2019-08-27 22:02 (192.168.144.1)
sun      :0           2019-08-27 20:04 (:0)
[root@localhost ~]# Pkill-9-U sun //Force sun customer offline
[root@localhost ~]# who //view logged-in users
root     pts/0        2019-08-27 22:02 (192.168.144.1)   //sun user kicked

Planned Task Management

On Linux operating systems, in addition to the command actions that users perform immediately, you can also configure to perform pre-planned system management tasks (such as periodic backups, periodic collection of monitoring data) at specified times and dates.By default, at and cronie software packages are installed in the CentOS system. The two system services, atd and crond, are used to schedule tasks once and periodically, and the tasks are set by at and crontab commands respectively.

at one-time task settings

When setting up a one-time scheduled task, specify in turn the time and date of the scheduled task on the at command line as parameters (if only the time is specified then the time of the day, if only the date is specified then the current time of the date). After confirmation, the task editing interface with the "at>" prompt will be entered, with each line set.An execution command can set several statements in turn, and then press Ctrl+D to submit the task.The set command actions will be executed sequentially at the scheduled point in time.

  • Command Format

    at [HH:MM] [YYYY-MM-DD]

  • atq command: view planned tasks
  • atrm [serial number]: delete task
[root@localhost ~]# date //Get the current time
2019 Tuesday, 27 August 2003:40:32 CST
[root@localhost ~]# at 23:45 2019-08-27//Set up one-time scheduled tasks to execute at 23:45
at> ps aux | wc -l > /opt/ps.txt      //Enter instructions to view the process and statistics to generate a file ps.txt
at> <EOT>                           //Press Ctrl+D key combination to submit task after input
job 1 at Tue Aug 27 23:45:00 2019    
[root@localhost ~]# atq //View planned tasks
1   Tue Aug 27 23:45:00 2019 a root
[root@localhost ~]# date //Get the current time
2019 Tuesday, 27 August 2003:46:51 CST
[root@localhost ~]# Ls/opt //See if the scheduled task is executed, see if the file is generated
data  ps.txt  rh                    //Successfully generated file ps.txt
[root@localhost ~]# date
2019 Tuesday, 27 August 2003:49:42 CST
[root@localhost ~]# at 23:53 2019-08-27//Set up one-time scheduled tasks to execute at 23:53
at> ps aux | wc -l > /opt/ps1.txt        //Enter instructions to view the process and statistics to generate the file ps1.txt
at> <EOT>                                 //Press Ctrl+D key combination to submit task after input
job 2 at Tue Aug 27 23:53:00 2019
[root@localhost ~]# atq //View planned tasks
2   Tue Aug 27 23:53:00 2019 a root
[root@localhost ~]# atrm 2 //Delete Scheduled Task 2
[root@localhost ~]# atq //View planned tasks
[root@localhost ~]#                     //Successfully deleted

crontab Periodic Task Settings

Scheduled tasks set with the crontab command can be repeated over a preset period, greatly reducing the need to set up repetitive system management tasks.There is also a precondition for enabling periodic tasks, that is, the corresponding system service crond must already be running.

1. Configuration files and directories for crontab

  • /etc/crontab - System Task Profile
[root@localhost ~]# cat /etc/crontab
SHELL=/bin/bash                             //Set Shell Environment for Scheduled Tasks 
PATH=/sbin:/bin:/usr/sbin:/usr/bin          //Define paths to executable commands and programs 
MAILTO=root                                 //Send task output information to mailbox of specified user 

# 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
  • )/var/spool/cron/- Directory where the user Cron task's profile is stored

    The cron scheduled task set by the user will be saved to the directory/var/spool/cron/with the same file name as the user name.

2. Manage users'scheduled tasks using the crontab command

  • Command Format

    crontab [options] [-u username]

  • Common Options

    -e: Edit scheduled tasks

    -l: View scheduled tasks

    -r: Delete scheduled tasks

  • Periodic Scheduled Task Writing Format

    * * * * * run_command
    field Meaning Explain
    * Minute Any integer between 0 and 59
    * hour Any integer between 0 and 23
    * date Any integer between 1 and 31
    * Month Any integer between 1 and 12
    * week Any integer between 0 and 7, 0 or 7 for Sunday
    run_command command Command or program script to execute
  • Special representations of time values
    "*": indicates any time in the range

    ",": Represents several discontinuous points of time at intervals

    "-": Represents a continuous time range

    '/': specify the interval time frequency

    [root@localhost ~]# Crontab-e //Edit periodically scheduled tasks

3300/usr/bin/cp-r/home/sun/opt///execute the copy command at 00:33 a day
~
~
: wq //Save Exit
[root@localhost ~]# crontab-l //View periodically scheduled tasks
33 00/usr/bin/cp-r/home/sun/opt///set periodic scheduled task
[root@localhost ~]# crontab-r //Delete periodically scheduled tasks
[root@localhost ~]# crontab-l //View periodically scheduled tasks
no crontab for root //Periodically scheduled tasks not set


Thank you for watching. Hope you can help us!!!

Keywords: Linux crontab vim Session

Added by crees on Tue, 27 Aug 2019 21:14:23 +0300