100% found this document useful (2 votes)
285 views22 pages

Ch9 - Monitoring and Managing Processes

Uploaded by

mody.20.fa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
285 views22 pages

Ch9 - Monitoring and Managing Processes

Uploaded by

mody.20.fa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

IOS203_Ch09

Chapter 9: Monitoring and Managing Processes

What is a Process?....................................................................................... 3
Signals ....................................................................................................... 11
Scheduling Priority .................................................................................... 14
Job Control ................................................................................................ 15
Scheduling Tasks ....................................................................................... 16

1
IOS203_Ch09

Objectives
Upon completing this chapter, the student should be able to:

 Understand what a process is;


 Monitor processes;
 List, identify, suspend and kill processes;
 Adjust some process priorities;
 Schedule commands for future execution.

Keywords
Process, interactive process, daemon, ps, pstree, top, fork, exec, signal, kill, killall, pkill,
nice, renice, jobs, fg, bg, atd, crond, crontab.

2
IOS203_Ch09

On Linux and other OSs, a program is a set of machine code instructions and data stored in an
executable file on disk. When a single command name is typed, a program related to that
command is run and the operating system creates process(es) for it. Therefore, a process can be
considered as a computer program in action or running program. As a Linux administrator, you
need to identify processes, manage foreground and background processes, kill them, or adjust
some process priorities. System and user processes have similar behaviors, so you can use a single
set of tools to monitor and manage both of them.

1. What is a Process?

Almost everything happening in a Linux system requires a process to be done. If you are editing
this text in a text editor, that editor is running as a process. If you are typing the cat ~/.bashrc
command line at a bash shell's command line, that shell is running as a process. When pressing
on the Enter key to execute the previous command line, the cat command operates as a separate
process.

In Linux, the terms task and process are used interchangeably. A process is an instance of a
running program; it is the abstraction through which memory, processor time, and I/O resources
can be managed and monitored [1]; it consists of an address space, which is laid out randomly in
the physical memory, and a set of data structures within the kernel. The address space contains
the code and libraries that the process is executing, its stacks and variables, and other information
needed by the kernel while the process is running. Therefore, the primary responsibility of the
Linux kernel is to provide a place for processes, manage and monitor them. The memory place for
a process often contains the following information: process’s owner, process’s address space
map, current process’s status, current process’s priority, CPU status, memory status, I/O
components (opened files and network ports) and process’s signal mask (a record of which signals
are blocked).

Processes are classified into two categories: interactive and daemon. Interactive process is a
process initialized and controlled through a shell prompt (or a terminal window). It needs
someone to connect to the system and starts it. On the other hand, daemon process usually starts
automatically as part of the system functions, run in the background rather than under the direct
control of a user, waiting to be activated by the occurrence of a specific event or condition. They
have names that end with the letter ‘d’ (e.g., sshd which handles SSH remote access connections).
On the Microsoft Windows operating systems, programs called services perform the functions of
daemons.

ps command
The ps (abbreviation of process status) command is used to display all currently running
processes; it reads this information from the virtual files in /proc filesystem.

When using the ps command without options or arguments, it lists the running processes in the
current shell:

3
IOS203_Ch09

Where:

 PID is the unique process ID;


 TTY represents the terminal to which the user is logged in;
 TIME is the time in minutes and seconds that the process has been running;
 CMD is the command that launched the process.

The most common options of the ps command are shown in the following table:

Option Description
View all processes except both session leaders and processes not associated
-a
with a terminal (session leader is the processes that has PID = session ID)
-e or –A View all the running processes
List the processes without a controlling terminal. Those are mainly
-x
processes that are started on boot time and running in the background
-u User-oriented format that provides detailed information about the processes
-t tty View all processes of the selected tty
-u username View all processes of the selected username
-p pidlist View information concerning the processes specified by their PIDs
-f "full" listing
-l, l long format
-j, j jobs format

Here are some examples:

4
IOS203_Ch09

Where PGID is the process group ID or, equivalently, the process ID of the process group leader,
and SID is the session ID or, equivalently, the process ID of the session leader.

Where UID is the effective user ID, PPID is the parent process ID, C is the processor utilization and
STIME is the starting time or date of the process.

5
IOS203_Ch09

Where F is the flag associated with the process, S is the process state, PRI is priority of the process
(higher number means lower priority), NI is the nice value, ADDR is the process structure, SZ is
the virtual address size of the process and WCHAN is the address of the kernel function where
the process is sleeping.

pstree command
By default, pstree utility is not installed on your CentOS 7. To install it execute the following
command line:

[root@StudentHost ~]# yum install psmisc


The pstree command displays a tree of processes:

The following table represents some common options of pstree command:

Option Description
-a View how the process was started (i.e., show command line arguments)
-h Highlight the current process and its ancestors
-p Show PIDs
-n Sort processes with the same ancestor by PID instead of by name

6
IOS203_Ch09

Here is an example:

The systemd process (with PID =1) is the root of the process tree.

top command
This command can be used to monitor all running processes. While the ps command displays
information about specified processes at the instant that the command is run, the top command
is used to monitor the general state of all running processes on the machine. When executing this
command, a table is shown on the screen. The table contains information about currently running
processes and is updated each few seconds (each three seconds by default). The following shows
you a screenshot of the top command output:

7
IOS203_Ch09

The first line represents Uptime and Load Averages:

Value Description
11:44:55 Current system time
26 min The time the system is been up
2 users Number of users logged in
0.04, 0.03, 0.05 CPU average load in 01, 05, and 15 Min

The second line represents Tasks:

Value Description
70 total Total processes in active mode
2 running Current running processes
68 sleeping Total processes in sleep mode
0 stopped Number of processes that have been stopped
Total processes in zombie state, they are waiting to be stop
0 zombie
from the parent process

The third line represents the CPU States:

Value Description
0.0 us CPU utilization of user processes
0.7 sy CPU utilization of system processes
0.0 ni CPU utilization of niced user processes
99.3 id CPU not used
0.0 wa CPU time waiting for IO completion
0.0 hi CPU serving hardware interrupts
0.0 si CPU serving software interrupts
CPU ‘stolen’ from this virtual machine by the hypervisor
0.0 st
for other tasks

8
IOS203_Ch09

The fourth line represents Memory Usage; it shows system total memory, free memory, current
memory utilization and total memory used by Buffers.

The fifth line represents Swap utilization status; it shows system total swap memory, free
memory, current memory utilization and cached swap space.

The sixth line represents fields (columns):

Field name Description


PID The process ID.
USER Owner of the process.
PR Priority of the process.
NI Nice value of the process.
VIRT Virtual memory used by the process.
RES Process physical memory.
SHR Process shared memory.
 Status of the process
 S: Sleep
 R: Running
S
 Z: Zombie
 T: Traced or stopped
 D: Uninterruptible sleep
%CPU CPU using by the process in percentage.
%MEM RAM using by the process in percentage.
TIME+ Total time of activity of this process.
COMMAND Command which was used to start the process

Process life cycle


On startup, the systemd process (PID = 1) starts and all subsequent processes are derived from it
by the fork-exec technique.

Figure 1: The fork-exec mechanism

When a process calls fork, it creates an exact copy of itself. The copy process becomes child, while
the original process becomes parent. The child inherits an identical copy of the original process's
memory, any open files of the parent, and identical copies of any parameters of the parent, such
as the current working directory or umask. The child has a different process ID from the process
ID of its parent.

9
IOS203_Ch09

On success, the PID of the child process is returned in the parent, and 0 is returned in the child.
On failure, -1 is returned in the parent and no child process is created.

When the child process calls exec, the current process image is replaced with a new process
image. The main difference between fork and exec is that when a new process executes exec, no
new process is created. The calling process is overwritten by the program whose file name is
passed by an exec call in the newly created child process. The child process execs the program to
be executed. So, fork and exec are mostly used together.

Some programs may use exec without fork. Examples of this situation include the login command,
which becomes the user's login shell after successfully confirming a user's password. Some
programs may use fork without exec. Examples of this situation include networking daemons,
who fork a new child to handle a specific client connection, while the parent goes back to listen
for new clients.

Figure 2: fork-exec Example

When running a command, the bash shell first forks a new bash shell. The child then execs the
appropriate command, while the parent waits for the child to die, and then issues another
prompt.

A process dies either normally by electing to exit, or abnormally as the result of receiving a signal.
When a process dies, it leaves behind a status code in the form of a return integer value (Recall
the bash shell, which uses the $? variable to store the return value of the previously run
command). When a process exits, all of its resources are freed, except the return code (and some
resource utilization accounting information). It is the responsibility of the process's parent to
collect this information, and free up the last remaining resources of the dead child. For example,
when the bash shell forks and execs the chown command, it is the parent bash shell's
responsibility to collect the return value from the exited chown command.

10
IOS203_Ch09

The parent process is responsible for cleaning up after their children. What happens if the parent
dies before the child does? The child becomes an orphan. One of the special responsibilities of
the first process started by the kernel is to "adopt" any orphans.

When a process exits, the child process passes through a transient zombie state. The zombie state
begins when freeing most of the process resources, and ends when its parent collects its return
value and frees the rest of its resources. Usually, users need to be looking at just the right time
(with the ps command, for example) to witness a zombie. They show up in the list of processes,
but take up no memory, no CPU time, or any other system resources. They are just the shadow of
a former process, waiting for their parent to come and finish them off.

2. Signals

Signals are software interrupts, they interrupt the normal flow of execution of a program, and
their arrival is unpredictable. A signal is a notification to a process that an event has occurred; it
can be sent by the Kernel or another process.

The kernel sent signals when a user types a command such as Ctrl+c (interrupt) or Ctrl+z
(suspend). Moreover, it could sent signals when a hardware exception has occurred and the
process must be notified, or when some software event occurred outside a process’s control but
effects the process.

Upon receiving a signal, a process may either ignore it, react in a kernel specified default manner,
or implement a custom signal handler.

kill command
This command is used to send custom signals to other processes. When using with –l option, the
kill command lists the signal names and their numbers.

The most common signals used by users are represented in the following table:

Number Symbol Description


Interrupt (request termination) of the process. This is the signal
2 SIGINT generated by the CTRL+C control sequence; it is one of the weakest kill
signals.

11
IOS203_Ch09

This signal is known as the absolute kill signal, it forces the Linux kernel
9 SIGKILL to stop executing the process by sending the process’s resources to the
/dev/null device.
The software termination signal is the most common kill signal used by
15 SIGTERM programs to kill other processes. This signal is the default kill signal used
by the kill command.
Stop typing at terminal (suspend the process). This is the signal
20 SIGTSTP
generated by the CTRL+Z control sequence.

The command kill %n terminates the background job n by sending the SIGTERM signal. Here is an
example:

The most frequently-used signal is SIGKILL or -9, which terminates a given process:

12
IOS203_Ch09

The killall command delivers signals to processes specified by command name:

The most common options used with killall command are:

 -i : interactively ask for confirmation before killing;


 -w : wait for all killed processes to die before returning.

pkill command
This command allows you to kill processes by name, terminal or user. Here are some examples:

[root@StudentHost ~]# pkill -9 –u raddad


This command line kills all processes belonging to the user raddad.

[root@StudentHost ~]# pkill -9 –t tty2


This command line kills all processes issued on the terminal tty2.

13
IOS203_Ch09

[root@StudentHost ~]# pkill -9 sleep


This command line kills all processes named sleep.

The following represents another example with its output:

3. Scheduling Priority

One of the main task of the Linux kernel is scheduling processes. Therefore, each process has a
nice value that influences its scheduling. This nice value may range from -20 to 19 for any process,
starting at 0 by default. The more the nice value is small, the more the process priority is high.

Two commands are useful to modify the priority of a given process. While the nice command lets
you execute a program/process with modified scheduling priority, the renice command allows
you to change the scheduling priority of an already running process.

nice command
This command is useful to run a program (or another command) with modified scheduling priority.
The syntax of the nice command is:

$ nice –n command|program
Where n belongs to the interval [-20, +19]. The following shows an example:

[raddad@StudentHost ~]$ nice –8 ./MyScript.sh

Note: The syntax can be misleading. The token -8 should not be considered negative 8 as a nice
value. It means running the ./MyScript.sh program with nice value = 8 instead of 0.

A regular user can decrease the process priority by increasing the default nice value of the process.
Only privileged users (i.e., root) can increase the process priority by decreasing the default nice
value of the process.

14
IOS203_Ch09

renice command
This command can be used to change the nice value of an already running process. Only root user
can execute the renice command.

If you have required privileges, you can use the top command to renice a process. While
monitoring processes with top, pressing r will open the following dialog above the list of
processes.

PID to renice: 29070


Renice PID 7347 to value: 19

4. Job Control

On Linux, processes could be run in the foreground or in the background. A foreground process is
any command or task you run directly and wait for it to complete; it begins by typing a command
at the shell prompt. While the computer is preparing and printing the command output, you
cannot do anything else from the command prompt. After showing the output on the screen, you
regain access to the shell prompt. Sometimes, you may want to run process in the background to
continue working on your command prompt while the background process finishes its work. Linux
system allows for a simultaneous process execution in the background. You will see a message on
the screen when a background process finishes.

A job, in Linux, is a task or command that has started running but not yet finished what it is doing.
Each running command is called a job, and is assigned a unique id called the job number.

jobs command
You can start commands directly in the background using ‘&’ and the jobs command is used to
list all background jobs. The following shows you how to let the tee command running in the
background and how to use the jobs command:

15
IOS203_Ch09

The ‘+’ sign next to the job number indicates the current job, that is the last job stopped while it
was in the foreground or started in the background whereas the previous job is always marked
with ‘-‘ sign. Therefore, we can refer to more recent job as ‘%’ or ‘%+’ and its previous job by ‘%-
‘. To resume a suspended process in the foreground, use the fg command and that process will
take over the active session.

The following command will put the job 1 in the foreground:

If a foreground process is taking too much time, you can stop and background it by pressing Ctrl+Z.
A stopped job still exists, but its execution is suspended. To resume the job, but in the background,
type bg to send the stopped job to background execution. The following example illustrates this
situation:

5. Scheduling Tasks

Two system daemons are responsible for running jobs scheduled for future execution:

 atd (or at daemon): it runs jobs that are one-time task (not repetitive) at a specific time
scheduled using the ‘at’ command;
 crond (or cron daemon): it runs jobs that are repetitive tasks in the future, those jobs are
written in the cron tables.

16
IOS203_Ch09

at command

This command allows you to submit jobs to the atd daemon to be run at a specific time. The
commands to be run are either submitted as a script (with the option -f), or entered directly via
CLI. The following table showing you how to specify the time of execution:

at Schedules commands to run


10:15pm at 10:15 pm on the current date
10:15pm July 15 at 10:15 pm on July 15
midnight at midnight on the current date
noon July 15 at noon on July 15
teatime at 04:00 pm on the current date
tomorrow the next day
now + 5 minutes in five minutes
now + 10 hours in ten hours
now + 4 days in four days
now + 2 weeks in two weeks
now immediately
9:00am 01/03/2018
9:00am 01032018 at 9:00 am on January 3, 2018
9:00am 01.03.2018

Here is an example:

In the previous example, the –m option is used to notify the user by email when the execution
result is done, even if there is no output. The –l option is used to list all scheduled jobs. The CTRL+D
is used to indicate an "end of file".

The atq command is equivalent to at –l command:

The –d option is used to delete a scheduled job:

The –f option followed by a file name is used to run the script specified by file name.

17
IOS203_Ch09

The atrm command is equivalent to at –d command:

The /var/spool/at directory is used for storing jobs; this should be mode 700. In addition, the
/var/spool/at/spool directory is used for storing output; this should be mode 700 also:

crontab command

The crond (i.e., cron daemon) is used to execute scheduled commands. This daemon checks the
following files and directories:

 /etc/crontab: system crontab. Nowadays the file is empty by default; it was originally
used to run daily, weekly, monthly jobs. By default, these jobs are now run through the
anacron command which reads /etc/anacrontab configuration file.

 /etc/cron.d/ directory that contains system cron jobs stored for different users.

18
IOS203_Ch09

 /var/spool/cron directory that contains user cron tables created by the crontab
command.

The crontab command is used to view or edit the table of commands to be run by the crond which
‘wakes up’ every minute to check those tables:

 If there are commands to run, it runs the commands;


 If nothing to do, it goes back to sleep for one minute.

The cron tables are files specifying tasks to be run by the cron daemon, they specify also when
commands should be executed. Each entry in a cron table contains six fields separated by space
or tab characters. The first five fields represent the time and date, while the last field represent a
command line to be run.

The time and date fields are shown in the following table:

Field Allowed values


minute 0-59
hour 0-23
day of month 1-31
month 1-12 (or names; see example below)
day of week 0-7 (0 or 7 is Sunday, or use names; see below)

Any of these fields can be set to an asterisk (*), which stands for "first through last". Here are
some examples showing you how to use time and date:

0011* : Run once a year (i.e., @yearly or @annually).

001** : Run once a month (i.e., @monthly).

00**0 : Run once a week (i.e., @weekly).

00*** : Run once a day (i.e., @daily or @midnight).

0**** : Run once an hour (i.e., @hourly).

@reboot : Run once after reboot.

The following is an example of a cron file content:

# use /bin/bash to run commands, no matter what /etc/passwd says


SHELL=/bin/bash
# mail any output to ‘Michel’, no matter whose crontab this is
MAILTO=Michel
#

19
IOS203_Ch09

CRON_TZ=Cairo
# run five minutes after midnight, every day
50*** $HOME/bin/daily.job >> $HOME/tmp/out 2>&1
# run at 2:15pm on the first of every month -- output mailed to paul
15 14 1 * * $HOME/bin/monthly
# run at 10 pm on weekdays, annoy Michel
0 22 * * 1-5 mail -s "It's 10pm" Michel % Michel,%%Where are your kids?%
5 4 * * sun echo "run at 5 after 4 every Sunday"

# Run the shell script /home/melissa/backup.sh on January 2 at 6:15 A.M


15 6 2 1 * /home/melissa/backup.sh

# Run /home/wendy/script.sh every Monday, at 9 A.M. and 6 P.M


0 9,18 * * Mon /home/wendy/script.sh

# Run /home/carl/hourly-archive.sh every hour, from 9 A.M. through 6 P.M., every day
00 09-18 * * * /home/carl/hourly-archive.sh

The following table represents the common options to be used with the crontab command:

Option Description
-u user Specifies the user whose crontab is to be viewed or modified. If this
option is not given, crontab opens the crontab of the user who
ran crontab. Note: using su to switch users can confuse crontab, so if you
are running it inside of su, always use the -u option to avoid ambiguity.
-l Display the current crontab.
-r Remove the current crontab.
-e Edit the current crontab, using the editor specified in the environment
variables.
-i Same as -r, but gives the user a yes/no confirmation prompt before
removing the crontab.

Here are some examples:

On CentOS and other RedHat based distros, the /etc/at.deny file lists all the users not able to use
the at command. This file is empty by default; it means all users allowed to use the at command.
In some Linux distros, the /etc/at.allow is used to list all users able to use at command.

20
IOS203_Ch09

atd an crond are processes like any other process. As other daemons, they are usually started as
part of the system's boot up sequence, or by the administrative user root; so if they are stopped,
you can start them again as follows:

anacron command

This command is used to execute commands periodically with a frequency specified in days.
Unlike the cron daemon, it does not assume that the machine is running continuously. Hence, it
can be used on machines that are not running 24 hours a day, to control regular jobs as daily,
weekly, and monthly jobs. When using the cron daemon, if a machine is not running on time of a
scheduled job then it will skip it. But, when using the anacron command, it first checks
for timestamp of the job then decides whether to run it or not and if its timestamp is >=n (n is
defined number of days) then runs it after a specified time delay. The anacron command is better
used when a job has to be executed irrespective of hour and minute (the time specified in days).
It is a good choice for desktops and laptops.

The anacron command reads /etc/anacrontab configuration file:

21
IOS203_Ch09

Questions
1. What is a Process?
2. What are the differences between daemons and interactive processes?
3. Explain the fields shown in the output of the command line: $ ps –l;
4. What is the main difference between ps and top?
5. Explain the fields shown in the output of the top command
6. Explain the fork-exec technique.
7. What is a zombie process?
8. What are the differences between SIGTSTP and SIGINT?
9. What is the difference between kill and pkill?
10. What is the difference between nice and renice?
11. When using the command line at teatime cmd; what time is teatime?
12. What is the difference between cron and anacron?
13. How to schedule a task in Linux?
14. What is crontab?
15. Explain the fields in the crontab file.
16. What are the process states in Linux?
17. How to stop a running process in Linux?
18. What is the main difference between atd and crond?
19. Which of the following commands can be used to schedule the execution of a command at a
specific time?
a. at b. later c. cron d. a and c

20. What is the name of the daemon that manages tasks submitted for later execution?
a. atd b. laterd c. crond d. batchd

References
1. unix-linux-system-administration-handbook-5th
2. Red Hat Linux Essentials RH033-RHEL5-en-2-20070306
3. Paul Cobbaut, “Linux Fundamentals”, https://linux-training.be/funhtml/index.html.
Updated on 2015-05-24

22

You might also like