Process monitoring in linux

How to check running process in Linux using command line

I am a new system administrator for the Linux operating system. How do I check running process in Linux using the command line option?

Tutorial details
Difficulty level Easy
Root privileges Yes
Requirements Linux terminal
Est. reading time 4 mintues

One can use the Linux command line or terminal app to display a running process, change their priorities level, delete process and more. This page shows how to use various commands to list, kill and manage process on Linux.

Check running process in Linux

The procedure to monitor the running process in Linux using the command line is as follows:

  1. Open the terminal window on Linux
  2. For remote Linux server use the ssh command for log in purpose
  3. Type the ps aux command to see all running process in Linux
  4. Alternatively, you can issue the top command or htop command to view running process in Linux

Let us see some example and usage in details.

Please note that vivek@nixcraft:

$ is my shell prompt. You need to type commands after the $ prompt.

How to manage processes from the Linux terminal

The ps command is a traditional Linux command to lists running processes. The following command shows all processes running on your Linux based server or system:
vivek@nixcraft:

$ ps -aux
vivek@nixcraft:

  1. root – User name
  2. 1 – PID (Linux process ID)
  3. 19:10 – Process start time
  4. /sbin/init splash – Actual process or command

There may be too many processes. Hence, it uses the following less command/more command as pipe to display process one screen at a time:
vivek@nixcraft:

$ ps -aux | more
vivek@nixcraft:

$ sudo ps -aux | less
Press q to exit from above Linux pagers. You can search for a particular Linux process using grep command/egrep command:
vivek@nixcraft:

$ ps aux | grep firefox
vivek@nixcraft:

$ sudo ps aux | grep vim
vivek@nixcraft:

$ sudo ps -aux | egrep ‘sshd|openvpn|nginx’

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Linux pgrep command

Many variants of Linux comes with the pgrep command to search/find process. The syntax is:
vivek@nixcraft:

$ sudo pgrep sshd
vivek@nixcraft:

$ pgrep vim
vivek@nixcraft:

$ pgrep firefox
vivek@nixcraft:

Linux top command

The top command is another highly recommended method to see your Linux servers resource usage. One can see a list of top process that using the most memory or CPU or disk.
vivek@nixcraft:

$ sudo top
vivek@nixcraft:

Linux htop command to check running process in Linux

The htop command is an interactive process viewer and recommended method for Linux users. One can see a list of top process that using the most memory or CPU or disk and more:
vivek@nixcraft:

$ sudo htop
vivek@nixcraft:

Linux kill command

Want to kill a process? Try kill command. The syntax is:
vivek@nixcraft:

$ kill pid
vivek@nixcraft:

$ kill -signal pid
Find PID using ps, pgrep or top commands. Say you want to kill a PID # 16750, run:
vivek@nixcraft:

$ kill 16750
For some reason if the process can not be killed, try forceful killing:
vivek@nixcraft:

$ kill -9 16750
OR
vivek@nixcraft:

$ kill -KILL 16750

Linux pkill command

If you wish to kill a process by name, try pkill command. The syntax is:
vivek@nixcraft:

$ pkill processName
vivek@nixcraft:

$ pkill vim
vivek@nixcraft:

$ pkill firefox
vivek@nixcraft:

$ pkill -9 emacs
vivek@nixcraft:

$ sudo pkill -KILL php7-fpm

Linux killall command

The killall command kills processes by name, as opposed to the selection by PID as done by kill command:
vivek@nixcraft:

$ killall vim
vivek@nixcraft:

$ killall -9 emacs

Linux nice and renice command

The primary purpose of the nice command is to run a process/command at a lower or higher priority. Use the renice command to alter the nice value of one or more running Linux processes. The nice value can range from -20 to 19, with 19 being the lowest priority. Say, you want to compile software on a busy Linux server. You can set a very low priority, enter:
vivek@nixcraft:

$ nice -n 13 cc -c *.c &
Set a very high priority for a kernel update. Before rebooting Linux server, run:

Источник

Мониторинг процессов Linux: топовые инструменты и какие сложности могут быть

Мониторинг процессов Linux — это своего рода вмешательство в работу этой операционной системы. В основном Линуксы в этом не нуждаются, если они работают нормально или вам не нужен от этой ОС нестандартный функционал.

Специфика работы Линукса в том, что он каждую отдельную программу запускает как отдельный процесс. И неважно , программа запускается «руками» или самой системой. Отдельный процесс в Линукс е можно представить как некий контейнер с отдельными инструкциями и информацией о ходе выполнения программы.

Процесс в Linux

Суть в том, что процесс в Линукс е — это и есть отдельная работающая программа в системе. Поэтому каждому рабочему процессу выделяется часть системных ресурсов и присваивается отдельный идентификатор, по которому чаще и проводят мониторинг процессов Linux. Каждому процессу присваивается отдельный PID (идентификатор) , и в работающей системе их может насчитываться тысячи. Отсчет начинается с PID1, а далее по возрастанию номер идентификатора увеличивается на единицу больше.

Чтобы провести мониторинг ресурсов системы Linux и проверить все запущенные процессы , обычно используют специальные утилиты. О них мы сегодня немного поговорим.

Как происходит мониторинг процессов Linux

Для того, чтобы провести мониторинг процессов Linux, есть большое количество разнообразных утилит. Есть многофункциональные и простые, ниже мы приведем список самых популярных из них:

Top. Это предустановленная утилита во многих системах Линукс, вводи тся прямо в Консоль и способна вывести информацию о всех запущенных процессах системы.

Htop. Используется как альтернатива первой утилиты, также способна показать все работающие процессы.

Atop. Его работа нагружает сервер, однако он немного функциональней первых двух утилит.

Apachetop. Способна промониторить трафик в онлайн — режиме и показать подробную информацию о трафике ваших веб — сайтов.

Ftptop. Покажет все запущенные ftp-соединения.

Mytop. Позволяет просмотреть все запросы к SQL.

Powertop. Определяет самые энергоемкие программы вашего компьютера на Линуксе.

Iotop. Похожа на утилиту top и выводит информацию об обращениях к hard-диску Linux.

Ntopng. Анализирует все IP-адреса, которые что-то скачивали с вашего сервера.

Iftop. Покажет все активные интернет-соединения, скорость сети, трафик и др.

Bandwidthd. Способна проконтролировать трафик пользователей.

EtherApe. Выводит сетевой трафик в виде графика: покажет поток, номер порта, активность в сети.

Ethtool. Используется для настройки сетевого интерфейса Линукс а .

NetHogs. Отследит и покажет любую сетевую активность.

Iptraf. Отслеживает весь трафик ТСР-соединений.

MRTG. Отследит все сетевые соединения и сгенерирует html-страницу с результатами.

Traceroute. В случае каких-то сбоев поможет отследить, где возник сбой.

IPTState. Покажет все открытые порты и разложит информацию в удобную таблицу.

Darkstat. Способна вывести подробные результаты использования сети.

Conky. Системный монитор с широким набором функций, выведет все основные показатели работы операционной системы.

Glances. Осуществит мониторинг всех процессов Linux в онлайн — режиме, выводит всю информацию на экран.

Saidar. Очень легкий инструмент, который выведет только основную информацию об ОС.

RRDtool. Это целый набор многофункциональных утилит, которые мониторят, хранят, обрабатывают и отображают любые данные, влияющие на работу системы.

Linux Process Explorer. Это графическая программа, которая проводит мониторинг системы Linux.

Discus. Покажет наличие свободного места в выбранной системе файлов ; если не задать систему, то программ а отобразит общую статистику всех систем.

XOSV iew. Классический инструмент для обзора процессов системы.

Dstat. Не только проведет качественный мониторинг системы, но и проанализирует производительность , продиагностирует сбои системы в онлайн-режиме.

Incron. Определяет все события, которые происходили в операционной системе.

Monitorix. Несложная утилита для мониторинга ресурсов системы, покажет все: от температуры процессора до обзора жестких дисков.

Gnome System Monitor. Осуществит эффективный мониторинг процессов Linux и выведет нужную информацию в виде простых графиков.

Всевозможных утилит огромное множество, представленные выше — это лишь небольшая часть утилит, которые могут быть использованы, чтобы осуществить полный или частичный мониторинг процессов Linux.

Мы будем очень благодарны

если под понравившемся материалом Вы нажмёте одну из кнопок социальных сетей и поделитесь с друзьями.

Источник

20 Command Line Tools to Monitor Linux Performance

It’s really a very tough job for every System or Network administrator to monitor and debug Linux System Performance problems every day.

After being a Linux Administrator for 10 years in the IT industry, I came to know that how hard is to monitor and keep systems up and running.

For this reason, we’ve compiled the list of Top 20 frequently used command line monitoring tools that might be useful for every Linux/Unix System Administrator.

These commands are available under all flavors of Linux and can be useful to monitor and find the actual causes of performance problems. This list of commands shown here is very enough for you to pick the one that is suitable for your monitoring scenario.

Linux Command Line Monitoring

1. Top – Linux Process Monitoring

Linux Top command is a performance monitoring program that is used frequently by many system administrators to monitor Linux performance and it is available under many Linux/Unix-like operating systems.

The top command is used to display all the running and active real-time processes in an ordered list and updates it regularly. It displays CPU usage, Memory usage, Swap Memory, Cache Size, Buffer Size, Process PID, User, Commands, and much more.

It also shows high memory and cpu utilization of running processes. The top command is much useful for system administrators to monitor and take corrective action when required. Let’s see the top command in action.

Check Linux Running Processes

For more examples of Top command read: 12 TOP Command Examples in Linux

2. VmStat – Virtual Memory Statistics

Linux VmStat command is used to display statistics of virtual memory, kernel threads, disks, system processes, I/O blocks, interrupts, CPU activity, and much more.

Install VmStat in Linux

By default vmstat command is not available under Linux systems you need to install a package called sysstat (a powerful monitoring tool) that includes a vmstat program.

The common usage of vmstat command format is.

Vmstat System Monitoring Tool

3. Lsof – List Open Files

The lsof command is used in many Linux/Unix-like systems to display a list of all the open files and the processes. The open files included are disk files, network sockets, pipes, devices, and processes.

One of the main reasons for using this command is when a disk cannot be unmounted and displays the error that files are being used or opened. With this command, you can easily identify which files are in use.

The most common format for lsof command is.

List Open Files in Linux

For more usage and examples, read: 10 lsof Command Examples in Linux

4. Tcpdump – Network Packet Analyzer

The tcpdump command is one of the most widely used command-line network packet analyzer or packets sniffer programs that is used to capture or filters TCP/IP packets that are received or transferred on a specific interface over a network.

It also provides an option to save captured packages in a file for later analysis. tcpdump is almost available in all major Linux distributions.

Tcpdump – Network Packet Analyzer

5. Netstat – Network Statistics

The netstat is a command-line tool for monitoring incoming and outgoing network packets statistics as well as interface statistics. It is a very useful tool for every system administrator to monitor network performance and troubleshoot network-related problems.

Netstat – Monitor Linux Network Connections

While in present-day netstat has been deprecated in favor of the ss command, you may still discover netstat in your networking toolkit.

6. Htop – Linux Process Monitoring

htop is a much advanced interactive and real-time Linux process monitoring tool, which is much similar to Linux top command but it has some rich features like a user-friendly interface to manage processes, shortcut keys, vertical and horizontal views of the processes, and much more.

Htop – Linux System Process Viewer

htop is a third-party tool, which doesn’t come with Linux systems, you need to install it using your system package manager tool. For more information on htop installation read our article – Install Htop (Linux Process Monitoring) in Linux.

7. Iotop – Monitor Linux Disk I/O

iotop is also much similar to top command and htop program, but it has an accounting function to monitor and display real-time Disk I/O and processes.

iotop tool is much useful for finding the exact process and high used disk read/writes of the processes.

Install Iotop in Linux

By default, the iotop command is not available under Linux and you need to install it as shown.

The common usage of iotop command format is.

iotop – Monitor Linux Disk IO Usage

8. Iostat – Input/Output Statistics

iostat is a simple tool that will collect and show system input and output storage device statistics. This tool is often used to trace storage device performance issues including devices, local disks, remote disks such as NFS.

Install Iostat in Linux

To get the iostat command, you need to install a package called sysstat as shown.

The common usage of iostat command format is.

iostat – Monitor Disk IO Statistics

9. IPTraf – Real-Time IP LAN Monitoring

IPTraf is an open-source console-based real-time network (IP LAN) monitoring utility for Linux. It collects a variety of information such as IP traffic monitor that passes over the network, including TCP flag information, ICMP details, TCP/UDP traffic breakdowns, TCP connection packet, and byte counts.

It also gathers information of general and detailed interface statistics of TCP, UDP, IP, ICMP, non-IP, IP checksum errors, interface activity, etc.

IPTraf IP Network Monitor

10. Psacct or Acct – Monitor User Activity

psacct or acct tools are very useful for monitoring each user’s activity on the system. Both daemons run in the background and keep a close watch on the overall activity of each user on the system and also what resources are being consumed by them.

These tools are very useful for system administrators to track each user’s activity like what they are doing, what commands they issued, how much resources are used by them, how long they are active on the system etc.

psacct – Monitor Linux User Activities

For installation and example usage of commands read the article on Monitor User Activity with psacct or acct

11. Monit – Linux Process and Services Monitoring

Monit is a free open source and web-based process supervision utility that automatically monitors and manages system processes, programs, files, directories, permissions, checksums, and filesystems.

It monitors services like Apache, MySQL, Mail, FTP, ProFTP, Nginx, SSH, and so on. The system status can be viewed from the command line or using its own web interface.

Monit Monitor Linux System

12. NetHogs – Monitor Per Process Network Bandwidth

NetHogs is an open-source nice small program (similar to Linux top command) that keeps a tab on each process network activity on your system. It also keeps a track of real-time network traffic bandwidth used by each program or application.

Nethogs Monitor Network Traffic in Linux

For installation and usage, read our article: Monitor Linux Network Bandwidth Using NetHogs

13. iftop – Network Bandwidth Monitoring

iftop is another terminal-based free open source system monitoring utility that displays a frequently updated list of network bandwidth utilization (source and destination hosts) that passing through the network interface on your system.

iftop is considered for network usage, what ‘top‘ does for CPU usage. iftop is a ‘top‘ family tool that monitors a selected interface and displays a current bandwidth usage between two hosts.

iftop – Network Bandwidth Monitoring

For installation and usage, read our article: iftop – Monitor Network Bandwidth Utilization

14. Monitorix – System and Network Monitoring

Monitorix is a free lightweight utility that is designed to run and monitor system and network resources as many as possible in Linux/Unix servers.

It has a built-in HTTP web server that regularly collects system and network information and displays them in graphs. It Monitors system load average and usage, memory allocation, disk driver health, system services, network ports, mail statistics (Sendmail, Postfix, Dovecot, etc), MySQL statistics, and many more.

It is designed to monitor overall system performance and helps in detecting failures, bottlenecks, abnormal activities, etc.

Monitorix Monitoring

15. Arpwatch – Ethernet Activity Monitor

Arpwatch is a kind of program that is designed to monitor Address Resolution of (MAC and IP address changes) of Ethernet network traffic on a Linux network.

It continuously keeps watch on Ethernet traffic and produces a log of IP and MAC address pair changes along with a timestamp on a network. It also has a feature to send email alerts to administrators, when a pairing is added or changes. It is very useful in detecting ARP spoofing on a network.

Arpwatch – Monitor ARP Traffic

For installation and usage, read our article: Arpwatch to Monitor Ethernet Activity

16. Suricata – Network Security Monitoring

Suricata is a high-performance open-source Network Security and Intrusion Detection and Prevention Monitoring System for Linux, FreeBSD, and Windows.

It was designed and owned by a non-profit foundation OISF (Open Information Security Foundation).

17. VnStat PHP – Monitoring Network Bandwidth

VnStat PHP is a web-based frontend application for the most popular networking tool called “vnstat“. VnStat PHP monitors network traffic usage in nicely graphical mode.

It displays a total IN and OUT network traffic usage in hourly, daily, monthly, and full summary reports.

For installation and usage, read our article: Monitoring Network Bandwidth Usage

18. Nagios – Network/Server Monitoring

Nagios is a leading open source powerful monitoring system that enables network/system administrators to identify and resolve server-related problems before they affect major business processes.

With the Nagios system, administrators can able to monitor remote Linux, Windows, Switches, Routers, and Printers on a single window. It shows critical warnings and indicates if something went wrong in your network/server which indirectly helps you to begin remediation processes before they occur.

19. Nmon: Monitor Linux Performance

Nmon (stands for Nigel’s performance Monitor) tool, which is used to monitor all Linux resources such as CPU, Memory, Disk Usage, Network, Top processes, NFS, Kernel, and much more. This tool comes in two modes: Online Mode and Capture Mode.

The Online Mode is used for real-time monitoring and Capture Mode is used to store the output in CSV format for later processing.

Nmon – Linux Performance Monitoring tool

20. Collectl: All-in-One Performance Monitoring Tool

Collectl is yet another powerful and feature-rich command-line-based utility, that can be used to gather information about Linux system resources such as CPU usage, memory, network, inodes, processes, nfs, TCP, sockets, and much more.

Collectl Monitoring

We would like to know what kind of monitoring programs you use to monitor the performance of your Linux servers? If we’ve missed any important tool that you would like us to include in this list, please inform us via comments, and please don’t forget to share it.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

Читайте также:  Как узнать установлен ли драйвер видеокарты linux
Оцените статью