This article introduces the concept of processes in Linux, exploring fundamental aspects of process handling and management through practical, command-line examples.
Understanding Linux Processes
In Linux, a process represents a distinct task operating within the system, performing specific functions and utilizing system resources such as CPU processing time, memory allocation, and file system access. Processes may also interact with hardware devices. They provide a higher-level abstraction for interacting with the system, while the Linux kernel manages lower-level hardware interactions and resource allocation. A process is analogous to an executing computer program, encompassing the program’s code, data, current instruction pointer, and CPU register contents. During its execution, a process may utilize multiple CPU cores and dynamically allocate physical memory for data storage.
Read: Differences between a thread and a process
Process PID (Process ID)
Linux assigns each process a unique numerical identifier, known as the Process ID or PID. This PID is a five-digit number, ensuring that no two concurrently running processes share the same PID at any given time.
To determine the PID of a specific process, open your terminal and execute the following command:
pgrep process_name
For example, to find the PID of the Firefox web browser process, use the command:
Alternatively, the `pidof` command can be used to achieve the same result:
pidof process_name
For instance, to find the PID of the `dhclient` process (Dynamic Host Configuration Protocol client):
pidof dhclient
If you are unsure of the exact process name, refer to the subsequent section on listing active processes to identify processes and their corresponding PIDs.
Read: The structure of Linux operating system
Types of Processes in Linux
Linux categorizes processes into two primary types:
- **Background Processes:**
Background processes operate automatically or non-interactively, meaning they do not require direct user input or interaction. These processes, often referred to as daemons or services, run independently in the background, typically without displaying output or requiring direct user intervention.
- **Foreground Processes:** Frontend or foreground processes are interactive processes initiated directly by a user. These processes typically run in the foreground, such as applications launched from a terminal or through a graphical user interface. When a process runs in the foreground, it occupies the terminal and prevents other commands from being executed in the same terminal until it completes or is moved to the background.
Foreground and Background Processes in Practice: A Real-World Example
Let’s illustrate the concept of foreground and background processes using the `ping` command. Open your terminal and execute:
ping net2.com
As expected, you will observe the communication status with the specified domain’s server being updated every few milliseconds. The terminal window will continuously scroll as the `ping` command runs, indicating it is a foreground process actively displaying output. To terminate the `ping` command, press `Ctrl+C`.
The `Ctrl+C` interrupt event is highlighted in the screenshot. After receiving this signal, `ping` ceases execution and presents a brief summary.
Now, repeat the `ping` command, but this time, press `Ctrl+Z` while the window is scrolling. This action will not terminate the `ping` process; instead, it will transform it into a background task, relinquishing control of the terminal back to the user.
ping www.net2.com
Ctrl+Z
Linux stop process using Ctrl+Z
As indicated in the final line of the output, pressing `Ctrl+Z` stops the process. However, “stopped” in this context does not mean terminated; it signifies that the process has been moved to the background and is now a background job.
To confirm this, execute the `jobs` command in your terminal:
jobs
The `jobs` command lists all active jobs initiated within the current terminal session. Let’s examine the output details:
**[1]** : This represents the job number. `[1]` indicates the default job, which is always the most recently added job to the list.
**Stopped** : This status indicates that the process is currently paused or suspended.
**ping net2.com** : This is the command that initiated the background process.
The `jobs` command provides a shell-specific view of jobs. Since jobs are fundamentally processes, they can also be viewed using process monitoring commands like `ps`. To demonstrate this, we will use the `ps T` command, employing the `T` option (terminal) to list only processes running within the current terminal window. Note that the hyphen `-` is not required with the `T` option.
Execute `ps T` to view jobs in the current terminal window:
Linux list processes in current terminal
The output columns represent:
**PID:** Process ID – the unique identifier of the process.
**TTY:** Teletype (TTY) – the terminal associated with the process.
**STAT:** Process State – the current execution state of the process.
**TIME:** CPU Time – the cumulative CPU time consumed by the process.
**COMMAND:** The command used to launch the process.
Observe the lowercase characters following the uppercase state indicators in the `STAT` column (e.g., `Ss` or `R+`). These secondary status codes provide additional details:
**`<`**: High-priority task.
**`N`**: Low-priority task.
**`L`**: Process has memory pages locked into RAM (typically real-time processes).
**`s`**: Session leader process (often a shell, which initiates process groups).
**`l`**: Multi-threaded process.
**`+`**: Foreground process group.
In the `ps T` output, the `ps T` command itself is in the `R` (Running) state, and the `+` indicates it’s in the foreground group, reflecting that `ps T` was executed as a foreground command.
The `bash` shell process is in the `Ss` state. `S` denotes Sleeping (interruptible), indicating it’s idle but responsive. `s` signifies that `bash` is a session leader.
Finally, the `ping` command is in the `T` state, indicating it is stopped due to a job control signal (`Ctrl+Z`).
Read: What to do when Ubuntu freezes
Resuming Background Processes: The `bg` Command
The `bg` (background) command resumes the execution of suspended background jobs. When a job is resumed with `bg`, it continues running in the background, returning the terminal prompt to the user, who cannot directly interact with the process.
Continuing our `ping` example:
As shown, the `ping` command is currently stopped in the background. To resume it, execute the `bg` command:
Linux run process in background using bg command
The `ping` command resumes execution in the background, and its scrolling output becomes visible in the terminal. The output of the `bg` command itself, as shown, includes the name of the restarted process (`ping net2.com`).
Attempting to stop the scrolling output by pressing `Ctrl+C` will not halt the background process because it is no longer in the foreground:
So, how do you stop a background process?
To terminate a background job, it must first be brought back to the foreground using the `fg` (foreground) command. This allows user input, such as `Ctrl+C`, to be directed to the process.
Bringing a Background Process to the Foreground: The `fg` Command
The `fg` command brings a background job to the foreground, making it the active process in the terminal. In our example, typing `fg` will bring the `ping` command back to the foreground, intermixing its output with the command-line prompt. The shell now treats the `ping` process as a standard foreground command.
Here’s the effect of typing `fg` while the `ping` output is scrolling:
Now that `ping` is in the foreground, pressing `Ctrl+C` will terminate it:
Parent and Child Processes
In Linux, each instance of a running program is a process, identified by a unique PID (Process ID) and a PPID (Parent Process ID). **Parent processes** initiate and spawn other processes during their execution, creating **child processes**. When a child process terminates before its parent, it becomes a zombie process until the parent process acknowledges its termination or determines it’s no longer relevant. If a parent process terminates before its child processes, the child processes are typically adopted by the `init` process or may be reassigned to another running process.
Process States in Linux
Understanding process states is crucial for effective Linux system troubleshooting. The Linux scheduler manages CPU core allocation among running processes, and the kernel interacts with and facilitates communication between processes. Familiarity with process states can significantly aid in diagnosing and resolving system performance issues:
- **Running/Runnable (R):** Processes in the Running state are actively executing on a CPU core. Runnable processes are ready to run and are waiting for an available CPU core to be scheduled for execution.
- **Waiting/Sleeping (S/D):** These processes are paused, awaiting a specific resource to become available (e.g., completion of an I/O operation) or for a specific event to occur (e.g., a timer expiration). Waiting processes can be further categorized:
* **Interruptible Waiting (S):** These processes can be awakened by signals, allowing their waiting state to be interrupted. They can be terminated by signals even before the awaited condition is met without adverse effects.
* **Uninterruptible Waiting (D):** These processes are in a deep sleep state and cannot be interrupted by signals or events, typically during critical I/O operations. They will resume processing only when the awaited operation completes and will then check for any pending signals. - **Stopped (T):** A process enters the Stopped state upon receiving a `SIGSTOP` signal (e.g., when `Ctrl+Z` is pressed in the terminal). Execution is suspended, and the process will only respond to `SIGKILL` (terminate immediately) and `SIGCONT` (continue) signals. Processes being debugged are often in a Stopped state.
- **Zombie (Z):** A Zombie process is in a terminated state but still has an entry in the process table. It has completed execution via the `exit()` system call but persists briefly until its parent process collects its exit status.
Refer to the following section for instructions on how to view and monitor system process states using various Linux utilities.
Process Signals in Linux
When you interrupt a foreground process like `ping` using `Ctrl+C` or suspend a background process with `Ctrl+Z`, you are actually sending signals to the process. Linux signals are a mechanism for inter-process communication and kernel-to-process notification. The `kill` command, despite its name, can send a variety of 64 different signals to processes, not just termination signals. To list available signals, use the command `kill -l`:
Alternatively, consult the `signal` manual page using `man signal`:
man signal
Processes use signals to communicate with each other and with the kernel. Signals can be sent using the `kill` system call, as well as the command-line utilities `pkill` and `killall`.
Commonly used signals include:
**SIGTERM (Signal 15):** The default signal sent by the `kill` command, requesting graceful termination.
**SIGKILL (Signal 9):** Forces immediate process termination without allowing cleanup or handling. Cannot be blocked or ignored.
**SIGCONT:** Resumes a stopped process, transitioning it to a running or runnable state.
**SIGSTOP:** Suspends process execution, moving it to the Stopped state. Triggered by `Ctrl+Z` in the terminal.
**SIGQUIT (Signal 3):** Generated by `Ctrl+\\` (Ctrl+D in some terminals). Forces process termination and a core dump (saving process memory to disk for debugging).
**SIGINT (Signal 2):** Generated by `Ctrl+C`. Interrupts the process and requests termination.
**SIGWINCH:** Generated when the terminal window size changes, often handled by interactive programs to redraw the display.
**SIGHUP (Signal 1):** Sent to a process when its controlling terminal disconnects (e.g., terminal window closure). `nohup` command can be used to prevent process termination upon terminal disconnection. Consider also the `screen` or `tmux` utilities for persistent sessions.
**SIGCHLD:** Sent by a child process to its parent process when its state changes (e.g., terminates, stops, or continues).
Read: How to kill a process in Linux – guide for beginners
The Init Process
The `init` process is the ancestor of all processes in Linux, acting as the root parent process. Typically assigned PID 1, `init` is the first process launched by the kernel during system boot and remains active until system shutdown. Its primary function is to initialize the system and create other processes based on the configuration script located at `/etc/inittab`. As it is directly started by the kernel, `init` has no parent process and cannot be terminated through signals.
Viewing Running Processes in Linux
Linux provides numerous utilities for monitoring and viewing running processes. The `ps` (process status) command is a widely used option:
ps ax
How to check running processes in linux using ps ax
Other Linux tools offer enhanced process viewing capabilities and additional information:
- htop Command: An interactive process viewer, offering a dynamic and user-friendly interface. Refer to our dedicated htop article for detailed information.
- atop Command: An advanced system and process monitoring tool providing comprehensive system performance insights.
- top Command: Displays a real-time, dynamically updated view of system processes, sorted by resource consumption.
- pstree Command: Presents a hierarchical tree view of processes, illustrating parent-child relationships.
- pgrep Command: Locates processes based on name and other attributes, primarily used for signal delivery and process identification.
- glances: A modern, cross-platform monitoring tool offering a consolidated view of system resources and processes. Visit its GitHub page or read our article for more details.
For a more comprehensive overview of these and other Linux monitoring tools, refer to our article available here.
Process Priority in Linux
Linux employs a priority system for processes, known as “niceness.” Processes with higher priority (lower “nice” values) receive preferential allocation of CPU time compared to lower-priority processes. The priority, or niceness, of a process can be adjusted by the root user using the `nice` and `renice` commands. The `top` command output includes the `NI` column, displaying the “nice” value for each process.
Linux process list showing niceness values
Standard users can utilize the `nice` utility to assign a “nice” value ranging from 0 (default) to 19 (lowest priority) to their own processes.
To launch a new program with a specific “nice” value, use the `nice` command followed by the `-n` option and the desired niceness level:
nice -n 10 command_to_run
To adjust the priority of a process that is already running, use the `renice` command, specifying the new niceness value and the PID of the target process:
renice +10 17544
Conclusion: Mastering Linux Processes
Linux processes are fundamentally categorized as foreground or background processes. Foreground processes are interactive and directly associated with a terminal, while background processes operate independently without direct terminal interaction. Linux offers a rich set of tools for managing processes, including `kill` for termination, `fg` for bringing background processes to the foreground, and `bg` for resuming background execution. Signals provide a crucial mechanism for communication between processes and the kernel, enabling process control and event notification. Understanding process management is an essential skill for both novice and advanced Linux users, empowering them to effectively control and optimize their systems.
If you like the content, we would appreciate your support by buying us a coffee. Thank you so much for your visit and support.