Operating Systems

Finding Resource-Hungry Scripts on Linux Servers with the htop Command

  • 17 min read
  • Hostragons Team
Finding Resource-Hungry Scripts on Linux Servers with the htop Command

The htop command on a Linux server is one of the most practical monitoring tools used to identify scripts that excessively consume CPU and RAM in real-time. By examining the CPU%, MEM%, PID, USER, TIME+, and COMMAND columns on the htop screen, you can easily spot which PHP, Python, Node.js, cron jobs, database, or system processes are straining the server. You can then check the process owner, file path, and purpose of the execution, allowing you to intervene safely.

Regardless of whether you're on shared hosting, VPS, VDS, or dedicated servers, a significant portion of sudden slowdowns stems from uncontrolled scripts. For instance, a faulty WordPress plugin, a PHP file stuck in an infinite loop, a cron job running intensively, an unoptimized database query, or a compromised web file can drive CPU usage close to 100% within minutes. When RAM consumption increases, services may hang, MySQL connections may drop, websites could return a 503 error, or the Linux kernel may terminate some processes using the OOM Killer.

In this guide, we will cover the installation of htop, how to read the screen, distinguish scripts that drain CPU and RAM, find the file path using PID, and how to intervene safely. We will also address security concerns, cron job checks, log analysis, and practical optimization suggestions to prevent recurrence. If you frequently encounter resource limits on your server, you may want to review your infrastructure choice by checking out VPS Server Packages and High-performance web hosting.

What is htop and Why is it More Useful than the top Command?

htop is an interactive terminal tool that allows you to monitor processes running on Linux systems. It is similar to the classic top command but offers a more readable interface, colorful resource indicators, easy sorting, searching, filtering, and process management features. For this reason, htop is often one of the first tools system administrators turn to for quick diagnoses on live servers.

With htop, you can instantly view the following information:

  • The CPU percentage used by each process
  • The RAM percentage and amount used by each process
  • The PID number of the process
  • The user running the process
  • The command line or script name
  • The uptime and priority value
  • Load average, total RAM, swap, and CPU core usage

Especially in a hosting environment where multiple sites, users, or services run on the same server, simply seeing total resource usage is not enough. You need to identify which user, website, cron job, or script is causing the issue. The htop command on a Linux server provides a quick first diagnosis at this point.

Installing htop: Commands Based on Your Distribution

Many modern Linux distributions may not come with htop pre-installed. If you have root or sudo privileges, you can install it in just a few seconds. Updating the package list before installation reduces the chance of errors, especially on newly set up servers.

Installing htop on Ubuntu and Debian Servers

On an Ubuntu or Debian-based server, you can use the following commands:

sudo apt update

sudo apt install htop -y

After installation, you can start the tool by typing the htop command. If you don’t have sudo privileges, you may need to request support from your hosting provider. If you are using a managed VPS, root access is usually yours.

Installing on AlmaLinux, Rocky Linux, CentOS, and RHEL

On RHEL-based systems, the package manager might be dnf or yum depending on the version:

sudo dnf install htop -y

On older CentOS versions, you may need the EPEL repository:

sudo yum install epel-release -y

sudo yum install htop -y

If the installation is successful, typing htop in the terminal will open the colorful monitoring screen. If you’re new to server management, our Linux Commands Guide provides a practical starting point for basic Linux commands.

Reading the htop Screen: What Each Column Means

When htop opens, the top part of the screen displays information about CPU cores, RAM, swap, the number of tasks, number of threads, load average, and uptime. The lower section lists the running processes. The most commonly used areas for troubleshooting are as follows.

Reading the htop Screen: What Each Column Means
Column Meaning When to Be Suspicious?
PID The unique identification number for the process. Necessary to examine the file path and connections.
USER The Linux user running the process. Should be checked if a process is running under an unexpected user.
CPU% The current CPU usage percentage of the process. Processes that remain in the 80-100% range for a long time should be examined.
MEM% The share of the total RAM occupied by the process. If a single script uses 20% or more RAM, it is risky.
TIME+ The total CPU time used by the process. Indicates long-term resource-consuming tasks, not short-term spikes.
COMMAND Information about the command, service, or script running. File paths should be searched in processes like php, python, node, perl, bash, java.

It’s important to note that a temporary spike in CPU usage is not always an issue. For example, backups, image optimization, cache clearing, or high traffic can cause transient CPU increases. The problem arises when the same process consumes high CPU or RAM for minutes, the load average value exceeds the number of cores significantly, and web services become unresponsive.

Finding CPU-Hungry Scripts with htop

To find scripts that excessively use CPU, you can select the sorting area by pressing the F6 key while in the htop screen, or sort by the CPU% column. In some terminals, if mouse support is enabled, clicking on the CPU% header may also suffice. The processes at the top are those currently using the most CPU.

Step 1: Sort by the CPU% Column

While htop is running, sort processes by CPU usage. For instance, if processes like php-fpm, php, python3, node, java, mysqld, or bash are consistently at the top, take note of that process. In single-core usage, 100% may seem like the normal upper limit, while in multi-core systems, a process might show values like 200% or 400%. This indicates that the process is using multiple cores.

Step 2: Note the PID and USER Information

Record the PID number and USER information of the suspicious process. For example, if PID 24819, USER as siteuser, and COMMAND shows php /home/siteuser/public_html/wp-cron.php, there’s a high chance that the issue relates to the cron mechanism or WordPress on the relevant website. If the COMMAND field is very short, you can enable showing the complete command line from htop settings or use the ps command to get details.

Step 3: View the Actual Command of the Process

To see the detailed command line via the PID, you can use the following command:

ps -fp PID

Example usage:

ps -fp 24819

This output usually shows which file the script is running from. If the command appears as php /home/user/public_html/index.php, it might be a web request caused by traffic. If it shows php /home/user/public_html/wp-content/plugins/unknown-plugin/task.php, it could indicate a plugin-related issue.

Step 4: Check the File Path and Open Files

The lsof tool is very valuable for seeing which files a process is using:

lsof -p PID

This command shows the files, libraries, logs, and network connections that the process has open. In web hosting environments, this output helps understand which site directory is active. For example, if you see a strangely named PHP file running in /home/example/public_html/wp-content/uploads, it may indicate a security breach. In such a case, merely terminating the process is not enough; file cleanup, password changes, plugin updates, and security scans should be carried out. For SSL and secure connection configurations, the SSL Certificate Solutions page can also be reviewed.

Finding RAM-Hungry Scripts with htop

RAM issues can progress more insidiously than CPU issues. While CPU spikes are usually felt as a transient slowdown, when RAM runs out, services can unexpectedly shut down, swap usage can increase, and overall server latency may rise. You can list the processes using the most memory by sorting according to the MEM% column on the htop screen.

Understanding the Relationship between MEM%, RES, and Swap

htop shows the MEM% ratio in its default view. In some configurations, VIRT, RES, and SHR columns may also be visible. When performing RAM analysis, the RES value is particularly important; it indicates the actual space used by the process in physical memory. The VIRT value does not always mean actual RAM consumption, so it can be misleading on its own.

For example, having a single PHP process using 900 MB RES on a VPS with 4 GB RAM is not normal. Similarly, a Node.js application growing from 200 MB to 1.5 GB over time raises the possibility of a memory leak. High RAM usage on the MySQL or MariaDB side can sometimes indicate normal caching behavior; here, query performance, buffer settings, and total system memory should be evaluated together.

Typical Reasons for RAM-Hungry Scripts

  • PHP, Python, or Node.js codes stuck in infinite loops
  • Loading large CSV, XML, or JSON files into memory all at once
  • Unoptimized WordPress plugins and theme functions
  • Image processing, PDF generation, or video conversion tasks
  • Repeated heavy queries due to insufficient caching
  • High instances of the same script due to bot traffic or attacks
  • Long-running background services with memory leaks

In such cases, merely using the kill command to shut down the process provides only temporary relief. A permanent solution requires analyzing what the script does, what inputs trigger it, and why it doesn’t free up memory.

Searching, Filtering, and Tree View in htop

If hundreds of processes are running on the server, manually searching through the list becomes difficult. htop offers useful shortcuts for this. You can search with F3, apply filters with F4, and switch to tree view with F5. The tree view is particularly important for seeing parent-child relationships. For example, you can more clearly see php-fpm child processes running under nginx or Apache, scripts triggered under cron, or Node.js services managed by supervisor.

Practical Filter Examples

  • Type php to view only PHP processes.
  • Type python to isolate Python scripts.
  • Type wp-cron to check WordPress cron behavior.
  • Type node to examine Node.js applications.
  • Filter by username to see the processes of a specific hosting account.

These filters save time, especially on multi-user servers. For instance, if 30 different sites are hosted on the same server, examining the USER column along with the command path quickly reveals which account the problem originates from. If you wish to streamline the management side for your domain-based projects, you can check out the Domain Lookup and Registration page.

Safe Intervention Plan for Suspicious PIDs

When you find a resource-hungry process, it may be tempting to immediately use kill -9. However, this approach can lead to data loss, incomplete write operations, or service inconsistencies. A safer plan should be followed.

1. Document the Process

First, note the PID, USER, COMMAND, CPU%, MEM%, and the time. If possible, take a screenshot of the htop screen. These records make it easier to compare recurring issues. Especially in agency, e-commerce, or corporate projects, this data can be useful when providing technical explanations to clients.

2. Verify the File Path of the Process

Verify the file path with ps -fp PID and lsof -p PID outputs. If the file is in the web root directory, check the logs of the relevant application. Important clues can be found in WordPress's wp-content/debug.log, the web server's access log and error log, and the PHP-FPM slow log.

3. Attempt Gentle Termination First

If the process is truly uncontrolled, first send the standard termination signal:

kill PID

Wait a few seconds and check the htop screen to see if the process has stopped. If it hasn’t and is seriously affecting system health, the following command can be used as a last resort:

kill -9 PID

The kill -9 signal terminates the process without giving it a chance to clean up. Therefore, it should be used cautiously for database operations, file writing processes, or backup tasks.

4. If It Restarts, Find the Trigger

If a process restarts within seconds of being closed, it may be triggered by cron, a systemd service, supervisor, a web request, or bot traffic. For cron logs, use crontab -l; for system services, check systemctl status service_name; and inspect the access log for web traffic. If the issue is due to WordPress wp-cron, the actual cron configuration and caching policy should be reviewed.

Combining htop Findings with Logs

Combining htop Findings with Logs

htop shows you what is consuming resources; logs help you understand why. When these two data sets are used separately, diagnosis remains incomplete. For example, a php-fpm process may be using 180% CPU on htop; without access logs, you may not see which URL or which bot triggered this process.

Examples of logs to check include:

  • Web server access log: Shows URLs receiving heavy requests.
  • Web server error log: Displays PHP errors, file permission issues, and 500 errors.
  • PHP-FPM slow log: Shows slow-running PHP files and functions.
  • MySQL slow query log: Identifies heavy SQL queries.
  • Auth log or secure log: Displays suspicious login attempts.
  • Cron log: Shows when scheduled tasks were executed.

For example, if the high CPU-consuming PID in htop shows thousands of requests to /wp-admin/admin-ajax.php in the access log during the same minute, the issue may lie with a plugin, bot traffic, or poorly designed AJAX processes. In this case, WAF, rate limits, caching, and plugin optimization should be considered together. To address website performance on a broader scale, our Website Speed Optimization content can be helpful.

How to Distinguish Between Normal Load and Problematic Load?

Not every high resource usage indicates a crisis. The server's hardware, traffic level, application type, and maintenance tasks must be taken into account. A load average value of 6-8 persisting for a long time on a 2-core VPS indicates a serious bottleneck. However, the same value may be normal on a 16-core dedicated server. Therefore, when interpreting load average, the number of cores must always be known.

How to Distinguish Between Normal Load and Problematic Load?
Observation Possible Situation Recommended Action
CPU spikes to 100% briefly, then returns to normal Temporary intensive processing Verify with logs; do not intervene immediately.
The same PID uses high CPU for minutes Infinite loop or heavy process Find the PID path; inspect the script.
RAM steadily increases and doesn’t decrease Memory leak Check service code and worker settings.
Swap usage rapidly increases Insufficient physical RAM Plan for RAM optimization or package upgrades.
Many instances of the same PHP process exist Bot traffic or heavy requests Check access log, firewall, and caching.

This comparison helps you differentiate between unnecessary panic and real performance crises. Especially in e-commerce sites, campaign periods, payment integrations, and inventory updates can cause temporary resource spikes. However, if this increase negatively impacts user experience, application optimization and server capacity should be evaluated together.

Security Concerns: Can Resource-Hungry Scripts Be Malicious?

Scripts that consume CPU or RAM may not always be innocent errors. On compromised websites, attackers can run scripts for spam sending, cryptocurrency mining, proxy traffic, DDoS bots, or backdoor scripts. Strange commands running under unexpected users, files with random names, binaries running from the /tmp directory, or PHP files operating within public_html/uploads on the htop screen should be taken seriously from a security standpoint.

Suspicious Signs

  • Meaningless or randomly named files in the COMMAND field
  • Files running from /tmp, /dev/shm, or uploads folders
  • Processes in Perl, Python, or Bash that should not normally exist
  • Processes creating high outbound network connections
  • The same user starting numerous processes in a short time
  • Recent unauthorized changes in web files

In such a case, before terminating the process, collect command outputs as evidence if possible. Then check file permissions, isolate malicious files, change all panel and CMS passwords, update core files of plugins and themes, and conduct a security scan. Additionally, implementing two-factor authentication in admin panels and removing unnecessary write permissions can reduce risks in the long term.

Best Practices to Prevent Recurrence of Performance Issues

Finding the problem with htop is essential, but the real value lies in preventing the same issue from happening again. The following measures significantly reduce CPU and RAM-related outages on Linux servers.

  • Adjust PHP memory_limit, max_execution_time, and pm.max_children values according to server capacity.
  • Use a caching mechanism in WordPress, Joomla, or custom software.
  • Remove unnecessary plugins, themes, and modules.
  • Optimize heavy queries with MySQL's slow query log.
  • Avoid stacking cron jobs to run at the same minute; schedule them intermittently.
  • Implement rate limits, robots.txt, and firewall rules for bot traffic.
  • Regularly rotate application logs; monitor the disk and RAM impact of massive log files.
  • Monitor server metrics regularly, not just during crises.

If resource usage remains consistently high despite optimizations, the problem may not solely lie on the software side. Traffic may have increased, the application may have grown, or the current hosting package may be insufficient. In this case, a scalable VPS, additional RAM, faster NVMe disk, or an isolated resource server becomes sensible. For needs analysis, options can be compared via Hosting Packages and Corporate Server Solutions.

Example Scenario: CPU Spike on a WordPress Site

Let's proceed with a realistic scenario. A VPS with 4 cores and 8 GB RAM is running several WordPress sites. Users report that the site is slowing down and occasionally receiving 502 errors. When htop is opened in the terminal, the load average is at 12, all CPU cores are full, and numerous php-fpm processes belonging to the same user are visible at the top.

Filtering by username with F4, the PID of one of the CPU-consuming processes is noted. The ps -fp PID output shows a php-fpm worker; using lsof -p PID reveals access to /home/site/public_html/wp-content/plugins/example-importer/import.php. Upon examining the access log, an admin request triggering this file and subsequent repeated AJAX calls are seen in the same minutes.

As a solution, the import process is halted, the plugin's scheduled task is disabled, the large data import is broken into smaller pieces, and the PHP max_execution_time limit is adjusted. Additionally, system cron is used instead of wp-cron. As a result, the load average drops from 12 to 1.8, CPU usage returns to normal, and web response times improve significantly. This example illustrates how effective htop can be when used alongside ps, lsof, and log analysis.

Common Mistakes Made While Using htop

  • Only terminating the top process without investigating the root cause.
  • Assuming VIRT value indicates actual RAM usage.
  • Directly considering MySQL's cache-related RAM usage as a problem.
  • Using kill -9 as the first option.
  • Blaming the application or user without checking logs.
  • Interpreting load average values independently of CPU core count.
  • Neglecting file integrity checks in case of security breach suspicions.

Avoiding these mistakes reduces downtime and lowers the risk of data loss due to incorrect interventions. Accurate diagnosis in system management is often more valuable than quick fixes.

Frequently Asked Questions

What does the htop command do on a Linux server?

The htop command on a Linux server provides real-time information on running processes, including CPU, RAM, user, PID, and command details. This allows you to quickly identify scripts that excessively use CPU or memory.

How do I find a CPU-consuming script with htop?

Sort processes by the CPU% column in the htop screen, note the PID and USER information of the process that remains at the top for a long time. Then verify the script's file path and what it is executing with the ps -fp PID and lsof -p PID commands.

Should I focus on MEM% or VIRT for RAM consumption?

For RAM analysis, MEM% and especially RES values are more meaningful. VIRT represents the amount of allocated virtual memory and does not always indicate physical RAM consumption.

Is it correct to immediately close a resource-consuming process with kill -9?

Generally, no. It’s safer to document what the process is, check the file path, and try the normal kill PID command first. kill -9 should only be used as a last resort when the process is not closing and is severely affecting server health.

Is high CPU usage in htop always a sign of an attack?

No. Backups, imports, cache creation, or high traffic can also increase CPU usage. However, strange file names, scripts running from /tmp or uploads, and unexpected user processes can raise security concerns.

In summary, the htop command on a Linux server is a quick, practical, and effective starting point for finding scripts that consume CPU and RAM. To achieve the best results, htop data should be combined with PID analysis, lsof output, cron checks, and log reviews. If resource issues frequently recur on your server, evaluate both software optimization and infrastructure capacity together; when needed, compare Hostragons' hosting, VPS, and SSL solutions without sales pressure to choose the most suitable setup for your project.

Share this article:

Hostragons Team

Up-to-date guides from our expert team on hosting, servers, and domain names. Let's find the right solution for your project together.

Contact Us