# Process Management

In Linux, a process is an instance of a running program, encompassing the program's code, current activity, and system resources such as memory, CPU, and file descriptors. Each process is uniquely identified by a Process ID (PID) and operates independently, though processes can communicate and interact through mechanisms like pipes, signals, or shared memory. Processes are created through a mechanism called "forking," where a parent process duplicates itself to create a child process, which can then execute a different program using the "exec" system call.

Process management in Linux involves controlling and monitoring these processes to ensure efficient system operation. The kernel handles process scheduling, resource allocation, and state transitions (e.g., running, sleeping, stopped, or terminated). Tools like `ps`, `top`, `htop`, and `pgrep` allow users to view and manage processes. Commands such as `kill`, `pkill`, and `nice` enable users to terminate processes, send signals, or adjust process priorities, respectively. The `init` process (or modern alternatives like `systemd`) acts as the root of all processes, managing system startup, shutdown, and orphaned processes. Effective process management ensures optimal system performance, resource utilization, and stability.

## Viewing Processes

In Linux, managing processes typically begins with identifying which processes are currently running on the system. The primary tool for this purpose is the `ps` command, which is indispensable for Linux administrators. When you run the `ps` command without any options, it displays a basic list of processes initiated by the currently logged-in user and running on the active terminal. For example, running `ps` might show output like this:

```bash
┌──(kali㉿kali)-[~/Desktop]
└─$ ps
PID TTY          TIME CMD
1377 pts/0    00:00:00 bash
1488 pts/0    00:00:00 ps
```

Here, the Linux kernel assigns a unique Process ID (PID) to each process sequentially as they are created. The PID is crucial because it is often required when performing actions on a specific process, such as terminating or prioritizing it. However, the default ps output is limited, showing only the processes associated with the current user and terminal. To gain a comprehensive view of all processes running on the system, including those initiated by other users and background system processes, you can use the ps aux command. This command provides detailed information about every process, as shown below:

```bash
┌──(kali㉿kali)-[~/Desktop]                                                                                                            
└─$ ps aux
USER         PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND                                                             
root           1  0.7  0.6  22560 13600 ?        Ss   05:44   0:00 /sbin/init splash                                                   
root           2  0.0  0.0      0     0 ?        S    05:44   0:00 [kthreadd]                                                          
root           3  0.0  0.0      0     0 ?        S    05:44   0:00 [pool_workqueue_release]                                            
root           4  0.0  0.0      0     0 ?        I<   05:44   0:00 [kworker/R-rcu_gp]                                                  
root           5  0.0  0.0      0     0 ?        I<   05:44   0:00 [kworker/R-sync_wq]                                                 
root           6  0.0  0.0      0     0 ?        I<   05:44   0:00 [kworker/R-slub_flushwq]                                            
root           7  0.0  0.0      0     0 ?        I<   05:44   0:00 [kworker/R-netns]                                                   
root           8  0.0  0.0      0     0 ?        I    05:44   0:00 [kworker/0:0-events]  
---snip---
```

The `ps aux` output includes a wealth of information, such as the user who started the process, the PID, CPU and memory usage, and the command that launched the process. Key columns to focus on are:

* **USER**: The user who initiated the process.
* **PID**: The unique process ID.
* **%CPU**: The percentage of CPU resources the process is using.
* **%MEM**: The percentage of memory the process is consuming.
* **COMMAND**: The command or program associated with the process.

This detailed view is essential for understanding system activity and managing processes effectively. By identifying the PID and other attributes, administrators can take specific actions, such as terminating unwanted processes or adjusting resource allocation, to maintain system performance and stability.

## **Filtering by Running Process**

When working with processes in Linux, it’s often unnecessary to view all running processes at once, as the sheer volume of information can be overwhelming. Instead, you typically want to focus on a specific process or a set of related processes. To achieve this, you can use the `grep` command to filter the output of `ps aux` and narrow down the results to only those processes that match a particular name or keyword. This approach is especially useful when dealing with resource-intensive applications or services.

For example, let’s consider the Apache web server, a widely used software for hosting websites. Suppose you want to check if Apache is running and assess its resource usage. You can start by filtering the `ps aux` output for processes related to Apache using the following command:

```bash
┌──(kali㉿kali)-[~/Desktop]
└─$ date                                                                                                                  
Fri Feb 28 05:58:14 AM EST 2025

┌──(kali㉿kali)-[~/Desktop]
└─$ service apache2 start

┌──(kali㉿kali)-[~/Desktop]
└─$ ps aux | grep apache2
root        7800  0.2  1.1 207752 22788 ?        Ss   05:58   0:00 /usr/sbin/apache2 -k start
www-data    7802  0.0  0.6 208584 12344 ?        S    05:58   0:00 /usr/sbin/apache2 -k start
www-data    7803  0.0  0.6 208584 12184 ?        S    05:58   0:00 /usr/sbin/apache2 -k start
www-data    7804  0.0  0.6 208584 12344 ?        S    05:58   0:00 /usr/sbin/apache2 -k start
www-data    7805  0.0  0.6 208584 12344 ?        S    05:58   0:00 /usr/sbin/apache2 -k start
www-data    7806  0.0  0.5 208584 12052 ?        S    05:58   0:00 /usr/sbin/apache2 -k start
kali        7836  0.0  0.1   6452  2320 pts/0    S+   05:58   0:00 grep --color=auto apache2
```

## **Identifying Resource-Intensive Processes Using `top`**

When you run the `ps` command, processes are displayed in the order they were started. Since the kernel assigns Process IDs (PIDs) sequentially, the output is essentially ordered by PID. However, in many cases, we’re more interested in identifying which processes are consuming the most system resources. This is where the `top` command becomes invaluable. Unlike `ps`, which provides a static snapshot of processes, `top` dynamically refreshes the list—by default, every 10 seconds—and sorts processes by resource usage, starting with the most demanding ones.

For example, running `top` in the terminal might display something like this:

```bash
┌──(kali㉿kali)-[~/Desktop]
└─$ top                                                                                                                   
top - 06:04:12 up 19 min,  2 users,  load average: 0.01, 0.06, 0.07
Tasks: 157 total,   1 running, 156 sleeping,   0 stopped,   0 zombie
%Cpu(s):  2.5 us,  4.6 sy,  0.0 ni, 92.3 id,  0.2 wa,  0.0 hi,  0.4 si,  0.0 st 
MiB Mem :   1974.1 total,    946.9 free,    722.8 used,    472.6 buff/cache     
MiB Swap:   1024.0 total,   1024.0 free,      0.0 used.   1251.3 avail Mem 

    PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND                                   
    693 root      20   0  509716 164036  79504 S  12.3   8.1   0:24.62 Xorg                                      
   1374 kali      20   0  466816 106632  92220 S   5.0   5.3   0:02.40 qterminal                                 
   1025 kali      20   0  983216 126004  83776 S   1.0   6.2   0:03.45 xfwm4                                     
   1086 kali      20   0  338100  27996  20756 S   0.3   1.4   0:02.16 panel-15-genmon                           
   1094 kali      20   0  385768  39456  31256 S   0.3   2.0   0:00.11 panel-22-action  
```

System administrators often keep `top` running in a terminal to monitor resource usage in real time. As a hacker, you might find this equally useful, especially when managing multiple tasks on your system. While `top` is running, you can press `H` or `?` to view a list of interactive commands, or press `Q` to exit

## **Managing Multiple Processes**

A hacker might run a port scanner alongside a vulnerability scanner and an exploit at the same time. To ensure optimal use of system resources and successful task completion, efficient process management is essential. In this section, I'll guide you through the steps to effectively manage multiple processes.

### Service and Process Management

Services can be broadly categorized into two types: **internal services** and **user-installed services**.

1. **Internal Services**: These are essential services required during system startup. They typically handle hardware-related tasks, system initialization, and core operating system functions. Examples include services that manage device drivers, network configurations, or system logging. These services ensure the system operates smoothly from the moment it boots up.
2. **User-Installed Services**: These are services installed by the user, often to enable specific functionalities or applications. Common examples include server services like web servers (e.g., Apache or Nginx), database servers (e.g., MySQL), or remote access tools (e.g., SSH). These services are designed to run in the background, operating without direct user interaction.

Services that run in the background are often referred to as **daemons**. Daemons are typically identified by the letter **'d'** at the end of their program names. For instance, `sshd` is the daemon for the SSH (Secure Shell) service, and `systemd` is a system management daemon responsible for initializing and managing other services during boot.

#### Starting a Service

```bash
┌──(kali㉿kali)-[~/Desktop]
└─$ systemctl start apache2
```

#### Checking Service Status

```bash
┌─(kali㉿kali)-[~/Desktop]
└─$ systemctl status <service_name>

┌──(kali㉿kali)-[~/Desktop]
└─$ systemctl status apache2
● apache2.service - The Apache HTTP Server
     Loaded: loaded (/usr/lib/systemd/system/apache2.service; disabled; preset: disabled)
     Active: active (running) since Fri 2025-02-28 10:03:37 EST; 3min 24s ago
 Invocation: 4dac895eb8844d5594c762d24647712f
       Docs: https://httpd.apache.org/docs/2.4/
    Process: 4671 ExecStart=/usr/sbin/apachectl start (code=exited, status=0/SUCCESS)
   Main PID: 4689 (apache2)
      Tasks: 6 (limit: 2219)
     Memory: 20.4M (peak: 20.7M)
        CPU: 90ms
     CGroup: /system.slice/apache2.service                                                                                             
             ├─4689 /usr/sbin/apache2 -k start                                                                                         
             ├─4693 /usr/sbin/apache2 -k start                                                                                         
             ├─4694 /usr/sbin/apache2 -k start                                                                                         
             ├─4695 /usr/sbin/apache2 -k start                                                                                         
             ├─4696 /usr/sbin/apache2 -k start                                                                                         
             └─4697 /usr/sbin/apache2 -k start                                                                                         
                                                                                                                                       
Feb 28 10:03:37 kali systemd[1]: Starting apache2.service - The Apache HTTP Server...                                                  
Feb 28 10:03:37 kali apachectl[4688]: AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 1>
Feb 28 10:03:37 kali systemd[1]: Started apache2.service - The Apache HTTP Server.                                                     
lines 1-21/21 (END)
```

#### **Terminating Processes**

Sometimes, a process may start consuming excessive system resources, behave abnormally, or even freeze entirely. Such a process is often referred to as a **zombie process**. Zombie processes can be particularly problematic because they waste valuable system resources that could otherwise be allocated to productive tasks. Identifying and terminating these problematic processes is an essential skill for maintaining system efficiency.

When you encounter a misbehaving process, you can stop it using the **`kill` command**. This command allows you to send specific signals to a process, instructing it to terminate or behave in a certain way. There are **64 different kill signals**, each serving a slightly different purpose. However, only a handful of these signals are commonly used in practice.

The basic syntax for the `kill` command is:

```
┌──(kali㉿kali)-[~/Desktop]                                                                                                            
└─$ kill -<signal> <PID>
```

#### Controlling Processes with Signals

Processes can be managed using commands like `kill`, `pkill`, `pgrep`, and `killall`. These tools allow you to send **signals** to processes, instructing them to perform specific actions such as terminating, pausing, or restarting. Each signal has a unique purpose and behavior.

#### Viewing Available Signals

To see a list of all available signals, you can use the following command:

```bash
┌──(kali㉿kali)-[~/Desktop]
└─$ kill -l                                                                                      
 1) SIGHUP       2) SIGINT       3) SIGQUIT      4) SIGILL       5) SIGTRAP
 6) SIGABRT      7) SIGBUS       8) SIGFPE       9) SIGKILL     10) SIGUSR1
---snip---
```

#### Common Signals and Their Uses

Below is a table of the most commonly used signals, along with their descriptions and typical use cases:

| Signal Number | Signal Name | Description                                                                                                            |
| ------------- | ----------- | ---------------------------------------------------------------------------------------------------------------------- |
| **1**         | SIGHUP      | Sent to a process when the terminal controlling it is closed. Often used to reload configurations (e.g., for daemons). |
| **2**         | SIGINT      | Sent when the user presses **Ctrl+C** in the terminal. Interrupts and terminates the process gracefully.               |
| **3**         | SIGQUIT     | Sent when the user presses **Ctrl+**. Causes the process to quit and generate a core dump (for debugging).             |
| **9**         | SIGKILL     | Forces the process to terminate **immediately** without cleanup. Use as a last resort for unresponsive processes.      |
| **15**        | SIGTERM     | Requests the process to terminate **gracefully**, allowing it to clean up resources before exiting.                    |
| **19**        | SIGSTOP     | **Pauses** the process. It cannot be handled or ignored by the process.                                                |
| **20**        | SIGTSTP     | Sent when the user presses **Ctrl+Z**. Suspends the process, but it can be resumed later.                              |

```jsx
┌──(kali㉿kali)-[~/Desktop]
└─$ ps aux | grep 'nano'
kali       44000  0.0  0.1   6956  3812 pts/0    S+   11:25   0:00 nano welcome.txt

┌──(kali㉿kali)-[~/Desktop]
└─$ kill -9 44000  # Forcefully kills the process with PID 44000
```

#### Killing a Process

```bash
┌──(kali㉿kali)-[~/Desktop]
└─$ ps aux | grep 'nano'
kali       13831  0.0  0.1   6956  3812 pts/0    S+   10:22   0:00 nano hello.txt
kali       13881  0.0  0.1   6452  2212 pts/2    S+   10:22   0:00 grep --color=auto nano

┌──(kali㉿kali)-[~/Desktop]
└─$ sudo kill 13831
```

#### Running Processes in the Background

In a command-line environment, you can run processes in the **background**, allowing you to continue using the terminal for other tasks while the process executes. This is particularly useful for long-running tasks, such as file transfers, compilations, or server operations, where you don’t need to monitor the process continuously.

**Using the `&` Operator**:

```bash
┌──(kali㉿kali)-[~/Desktop]
└─$ sleep 100 &                                                    
[1] 24213
```

**Moving a Process to the Background**

If you’ve already started a process in the foreground, you can pause it using <kbd>CTRL + Z</kbd> and then move it to the background with the `bg` command.

#### **Bringing a Background Process to the Foreground**

If you have a process running in the background and want to bring it back to the foreground, you can use the **`fg` (foreground)** command. This command allows you to resume control of the process in your terminal session.

Run the `jobs` command to list all background processes and their job IDs:

```bash
┌──(kali㉿kali)-[~/Desktop]
└─$ jobs                                                           
[2]+  Running    #job id            

┌──(kali㉿kali)-[~/Desktop]
└─$ fg %2          ## Here, [2] is the job ID for the sleep 400 process.                                                 
sleep 400
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://handbook.ncateam.xyz/fundamentals/linux/process-management.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
