Processes
Chapter 10
Contemporary operating systems are typically multitasking, simulating the execution of multiple tasks simultaneously by swiftly transitioning between executing programs. The Linux kernel oversees this functionality by utilizing processes. Processes serve as Linux's method of organizing various programs awaiting their turn for CPU execution.
Occasionally, a computer might slow down, or an application may freeze. In this chapter, we'll explore command-line tools that enable us to inspect program activities and manage unresponsive processes effectively.
This chapter will introduce the following commands:
ps– Report a snapshot of current processestop– Display tasksjobs– List active jobsbg– Place a job in the backgroundfg– Place a job in the foregroundkill– Send a signal to a processkillall– Kill processes by nameshutdown– Shutdown or reboot the system
How A Process Works
At system startup, the kernel initiates its own tasks as processes and triggers the init program. init executes a sequence of shell scripts (located in /etc) named init scripts, responsible for launching all the system services. A lot of these services are daemon programs, operating silently in the background without any user interface. Hence, even without a user logged in, the system is engaged in routine tasks.
The process system reflects a program's ability to spawn other programs by establishing a relationship where a parent process generates a child process.
The kernel manages process details to maintain system organization. This includes assigning a unique number to each process known as a Process ID (PID). PIDs start in ascending order, with init consistently receiving PID 1. Additionally, the kernel tracks memory allocation for each process and monitors their readiness to resume execution. Similar to files, processes are associated with owners, user IDs, effective user IDs, and more.
Viewing Processes
The ps command, among several options, is commonly used to display processes. Its most basic usage involves:
In this example, the output lists two processes: process 5198 and process 10129, which correspond to bash and ps, respectively. By default, the ps command offers limited information, displaying only the processes linked to the current terminal session. Before delving into additional options to gather more data, let's review the other fields provided by ps. The TTY field indicates the controlling terminal for each process, a legacy term reflecting Unix's origins. Meanwhile, the TIME field denotes the CPU time utilized by the process. In this case, neither process significantly strains the computer's resources.
If we add an option, we can get a bigger picture of what the system is doing:
Including the x option (without a leading dash) instructs ps to display all processes, irrespective of their associated terminal. A ? in the TTY column denotes the absence of a controlling terminal. Utilizing this option reveals a comprehensive list of all processes owned by the user.
As the system operates numerous processes, running ps generates an extensive list. To facilitate easier browsing, piping the ps output into less can be useful. Additionally, maximizing the terminal emulator window might aid in handling lengthy lines of output generated by certain option combinations.
The updated output now includes a new column labeled STAT, representing the "state" of each process, showcasing its current status.
R
Running. This means that the process is running or ready to run.
S
Sleeping. The process is not running; rather, it is waiting for an event, such as a keystroke or network packet.
D
Uninterruptible Sleep. Process is waiting for I/O such as a disk drive.
T
Stopped. Process has been instructed to stop. More on this later.
Z
A defunct or “zombie” process. This is a child process that has terminated, but has not been cleaned up by its parent.
<
A high priority process. It's possible to grant more importance to a process, giving it more time on the CPU. This property of a process is called niceness. A process with high priority is said to be less nice because it's taking more of the CPU's time, which leaves less for everybody else.
N
A low priority process. A process with low priority (a “nice” process) will only get processor time after other processes with higher priority have been serviced.
The process state might be accompanied by additional characters, denoting various distinct process traits. For more detailed insights, refer to the ps man page.
Another popular set of options is “aux” (without a leading dash). This gives us even more information:
These options reveal processes owned by all users. Without the leading dash, these options employ the "BSD style" behavior, mimicking various Unix implementations of the ps command. It results in displaying these additional columns:
USER
User ID. This is the owner of the process.
%CPU
CPU usage in percent.
%MEM
Memory usage in percent.
VSZ
Virtual memory size.
RSS
Resident Set Size. The amount of physical memory (RAM) the process is using in kilobytes.
START
Time when the process started. For values over 24 hours, a date is used.
Viewing Processes Dynamically With top
Although the ps command offers insights into the system's activity, it presents a static snapshot of the system at the time of execution. For a more dynamic view of the machine's activity, the top command is employed:
The top command generates a continuously updating system overview, typically refreshing every 3 seconds. Its name derives from its function to show the most active processes, presented in two sections: an overview of system metrics followed by a table of processes arranged by CPU usage:
The system summary contains a lot of good stuff. Here's a rundown:
1
top
Name of the program.
14:59:20
Current time of day.
up 6:30
This is known as uptime, indicating the duration since the system was last rebooted. In this instance, the system has been running for six and a half hours.
2 users
There are two users logged in.
load average:
Load average represents the count of processes waiting to execute, indicating those in a runnable state that share the CPU. Three metrics are displayed, each over a distinct time span: the average over the last 60 seconds, the previous 5 minutes, and finally, the preceding 15 minutes. Values below 1.0 suggest the machine isn't heavily occupied.
2
Tasks:
This summarizes the number of processes and their various process states.
3
Cpu(s):
This row describes the character of the activities that the CPU is performing.
0.7%us
0.7% of the CPU is being used for user processes. This means processes outside of the kernel itself.
1.0%sy
1.0% of the CPU is being used for system (kernel) processes.
0.0%ni
0.0% of the CPU is being used by “nice” (low priority) processes.
98.3%id
98.3% of the CPU is idle.
0.0%wa
0.0% of the CPU is waiting for I/O.
4
Mem:
Shows how physical RAM is being used.
5
Swap:
Shows how swap space (virtual memory) is being used.
The top program responds to various keyboard commands. Of these, the most notable are h, which brings up the program's help screen, and q, used to exit top.
Both major desktop environments offer graphical applications akin to top, much like Windows' Task Manager. However, I prefer top as it's faster and consumes fewer system resources. Our system monitor shouldn't be the cause of the slowdown we're trying to investigate.
Controlling Processes
Now that we're equipped to observe and manage processes, let's take control of them. For our experiments, we'll employ a program called xlogo. It's a sample program that comes with the X Window System, showcasing a resizable window with the X logo. First, let's acquaint ourselves with our test subject:
Upon entering the command, a small window displaying the logo should appear somewhere on the screen. Occasionally, xlogo might display a warning message on certain systems, but it can typically be disregarded.
We can confirm xlogo is running by resizing its window—if the logo adjusts to the new size, the program is active.
See how our shell prompt hasn't reappeared? It's because the shell is waiting for the program to finish, similar to our previous experiences. Once we close the xlogo window, the prompt will return.
Interrupting A Process
Let's see what occurs when we launch xlogo once more. Start by entering the xlogo command to confirm the program is running. Then, head back to the terminal window and press Ctrl-c.
In a terminal, using Ctrl-c interrupts a program, politely requesting it to terminate. Upon pressing Ctrl-c, the xlogo window closed, and the shell prompt reappeared.
Many (but not all) command-line programs can be interrupted by using this technique.
Putting A Process In The Background
Suppose we want to retrieve the shell prompt without terminating the xlogo program. We can do this by running the program in the background. Think of the terminal as having a foreground (where the visible elements like the shell prompt reside) and a background (where hidden processes operate). To start a program directly in the background, add an & at the end of the command:
Upon entering the command, the xlogo window appeared, and the shell prompt returned, accompanied by some numeric output. This message is part of a shell feature known as job control. It indicates that we've initiated job number 1 ([1]) with a PID of 43384. To check this process, we can use the ps command:
The shell's job control feature provides a way to display the jobs initiated from our terminal. By using the jobs command, we can view this list:
The output indicates a single running job, numbered as 1, executed through the command xlogo &.
Returning A Process To The Foreground
A process running in the background won't respond to keyboard inputs, such as Ctrl-c. To bring it back to the foreground, use the fg command like this:
Entering fg along with the percent sign and the job number (jobspec) brings a process to the foreground. If there's only one background job, the jobspec becomes optional. To end the xlogo program, use Ctrl-c.
Stopping (Pausing) A Process
Occasionally, we might need to pause a process without ending it, usually to shift a foreground process into the background. To pause a foreground process, hit Ctrl-z. Let's test this: type xlogo at the prompt, press Enter, and then Ctrl-z.
Once xlogo is paused, you can check its status by trying to resize the xlogo window, which won't respond. To bring it back to the foreground, use the fg command, or move it to the background with bg.
As with the fg command, the jobspec is optional if there is only one job.
Shifting a process from the foreground to the background is useful if we start a graphical program from the command line but forget to add the & symbol to run it in the background.
What motivates launching a graphical program from the command line? There are a couple of reasons. Firstly, certain programs like xlogo might not be available in the window manager's menus. Secondly, launching a program from the command line can reveal error messages that remain hidden when the program starts graphically. Occasionally, a program might fail to initiate via the graphical menu, but launching it from the command line can expose an error message, helping identify the issue. Additionally, some graphical programs offer numerous handy command line options.
Signals
The kill command helps terminate processes that need to be stopped. Here's how it works in action:
First, we initiate xlogo in the background, and the shell provides the jobspec and PID of this background process. Following that, we use the kill command to terminate the process by specifying its PID. Alternatively, we could have referenced the process using a jobspec (e.g., %1) instead of the PID.
This might seem straightforward, but there's more to the kill command—it doesn't actually "kill" processes outright; instead, it sends them signals. Signals are a means through which the operating system communicates with programs. We've already encountered signals in action through keystrokes like Ctrl-c and Ctrl-z. When these keystrokes are received, the terminal sends signals to the foreground program: Ctrl-c triggers a signal named INT (Interrupt), while Ctrl-z sends TSTP (Terminal Stop). Programs are designed to "listen" for signals and can react accordingly when they receive them. This capability allows programs to perform actions such as saving ongoing work when they receive a termination signal.
Sending Signals To Processes With kill
The kill command is typically used to dispatch signals to programs, and its standard syntax resembles this:
When no signal is specified in the command line, the default signal sent is TERM (Terminate). Commonly, the kill command is employed to dispatch the following signals:
1
HUP
Hangup, a signal stemming from the era of remote terminals connected via phone lines and modems, signifies the terminal's disconnection. When a terminal session is closed, the signal is sent to the foreground program, prompting its termination.
Daemon programs commonly utilize this signal for reinitialization purposes. For instance, when a daemon receives this signal, it restarts and re-examines its configuration file. The Apache web server is an example of a daemon employing the HUP signal for this function.
2
INT
Interrupt, much like the Ctrl-c key from the terminal, typically terminates a program by interrupting its execution.
9
KILL
The KILL signal is unique; it doesn't get sent to the target program as other signals do. Instead, the kernel promptly terminates the process. When a process ends this way, it has no chance to tidy up or save its work. Therefore, the KILL signal should be a final option when other termination signals are ineffective.
15
TERM
The "Terminate" signal, which is the default when using the kill command, prompts a program to terminate if it's still responsive enough to receive signals.
18
CONT
Continue. This will restore a process after a STOP signal.
19
STOP
"Stop" signal is used to pause a process without terminating it, much like the KILL signal; however, it's not directly sent to the target process and hence cannot be ignored.
Let's try out the kill command:
In this instance, we initiate the xlogo program in the background and subsequently issue a HUP signal using kill. This action leads to the termination of the xlogo program, prompting the shell to confirm the reception of a hangup signal by the background process. It might require a couple of presses of the enter key before you observe the message. Remember, signals can be identified either by number or by name, including the name with the SIG prefix.
Duplicate the previous demonstration and experiment with the alternate signals. Don't forget, you have the option to utilize jobspecs instead of PIDs.
Similar to files, processes also possess owners, and to send signals using kill, you need to be the process owner or the superuser.
Apart from the signals mentioned earlier, commonly utilized with kill, there's a set of additional signals frequently employed by the system. Here's a compilation of other prevalent signals:
3
QUIT
Quit.
11
SEGV
Segmentation Violation. This signal is sent if a program makes illegal use of memory, that is, it tried to write somewhere it was not allowed to.
20
TSTP
Terminal Stop. This is the signal sent by the terminal when the Ctrl-z key is pressed. Unlike the STOP signal, the TSTP signal is received by the program but the program may choose to ignore it.
28
WINCH
Window Change. This is a signal sent by the system when a window changes size. Some programs , like top and less will respond to this signal by redrawing themselves to fit the new window dimensions.
For the curious, a complete list of signals can be seen with the following command:
Sending Signals To Multiple Processes With killall
killallYou can also dispatch signals to multiple processes that match a particular program or username by employing the killall command. Here's the syntax:
As an illustration, we'll initiate a pair of xlogo program instances and subsequently conclude their operation:
Similar to using kill, possessing superuser privileges is necessary to send signals to processes that aren't owned by you.
More Process Related Commands
Given the significance of overseeing processes in system administration, there exists a multitude of commands for this purpose. Here are a few to explore:
pstree
Outputs a process list arranged in a tree-like pattern showing the parent/child relationships between processes.
vmstat
Outputs a snapshot of system resource usage including, memory, swap and disk I/O. To see a continuous display, follow the command with a time delay (in seconds) for updates. For example: vmstat 5. Terminate the output with Ctrl-c.
xload
A graphical program that draws a graph showing system load over time.
tload
Similar to the xload program, but draws the graph in the terminal. Terminate the output with Ctrl-c.
Summary
Many contemporary systems incorporate a system for handling numerous processes. Linux offers an extensive array of tools for this role. Considering Linux's status as the most prevalent server operating system globally, this approach is logical. However, unlike some other systems, Linux predominantly relies on command line tools for managing processes. Despite the existence of graphical process tools for Linux, the command line tools are highly favored due to their rapidity and minimal resource consumption. Although GUI tools might have an appealing appearance, they can impose a significant system load, somewhat counteracting their intended purpose.
Last updated