- Linux find process by name
- Procedure to find process by name on Linux
- Linux find process by name using pgrep command
- How to use ‘ps aux | grep command’
- Using pidof command to grab PIDs for any named program on Linux
- A note about top/htop command
- See also
- Getting more help
- Как узнать PID процесса в Linux
- Как узнать pid процесса Linux
- 2. pgrep
- 3. pidof
- 4. pstree
- Как узнать PID скрипта
- Каким процессом занят файл Linux
- Кто использовал файл в Linux
- Какой процесс использует порт в Linux
- Выводы
- How to check running process in Linux using command line
- Check running process in Linux
- How to manage processes from the Linux terminal
- Linux pgrep command
- Linux top command
- Linux htop command to check running process in Linux
- Linux kill command
- Linux pkill command
- Linux killall command
- Linux nice and renice command
Linux find process by name
Procedure to find process by name on Linux
- Open the terminal application.
- Type the pidof command as follows to find PID for firefox process:
pidof firefox - Or use the ps command along with grep command as follows:
ps aux | grep -i firefox - To look up or signal processes based on name use:
pgrep firefox
Linux find process by name using pgrep command
pgrep command looks through the currently running processes and lists the process IDs which match the selection criteria to screen. All the criteria have to match. For example, will only list the processes called sshd AND owned by root user:
$ pgrep -u root sshd
Just look up pid for firefox process:
$ pgrep firefox
How to use ‘ps aux | grep command’
ps command shows information about a selection of the active processes:
$ ps aux
$ ps aux | grep -i ‘search-term’
$ ps aux | grep ‘firefox’
$ ps aux | grep ‘sshd’
OR use the following syntax instead of using egrep command in pipes:
$ ps -fC firefox
$ ps -fC chrome
The -C option asks ps command to select PIDs by command name.
- 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 ➔
Using pidof command to grab PIDs for any named program on Linux
The pidof command finds the process id’s (pids) of the named programs such as sshd, firefox and more. For example:
$ pidof sshd
$ pidof firefox
Sample outputs:
A note about top/htop command
To display Linux processes use top command or htop command:
$ top
OR
$ htop
See also
Getting more help
Read the man pages for the following command using man command:
$ man pgrep
$ man pidof
$ man ps
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
Как узнать PID процесса в Linux
Каждый процесс в операционной системе имеет свой уникальный идентификатор, по которому можно получить информацию об этом процессе, а также отправить ему управляющий сигнал или завершить.
В Linux такой идентификатор называется PID, и узнать его можно несколькими способами. В этой статье мы рассмотрим, как узнать PID процесса в Linux, а также зачем это может вам понадобиться.
Как узнать pid процесса Linux
Самый распространённый способ узнать PID Linux — использовать утилиту ps:
ps aux | grep имя_процесса
Кроме нужного нам процесса, утилита также выведет PID для grep, ведь процесс был запущен во время поиска. Чтобы его убрать, добавляем такой фильтр:
ps aux | grep имя_процесса | grep -v grep
Например, узнаём PID всех процессов, имя которых содержит слово «Apache»:
ps aux | grep apache | grep -v grep
2. pgrep
Если вам не нужно видеть подробную информацию о процессе, а достаточно только PID, то можно использовать утилиту pgrep:
По умолчанию утилита ищет по командной строке запуска процесса, если нужно искать только по имени процесса, то надо указать опцию -f:
3. pidof
Эта утилита ищет PID конкретного процесса по его имени. Никаких вхождений, имя процесса должно только совпадать с искомым:
С помощью опции -s можно попросить утилиту выводить только один PID:
pidof -s apache2
4. pstree
Утилита pstree позволяет посмотреть список дочерних процессов для определённого процесса, также их pid-идентификаторы. Например, посмотрим дерево процессов Apache:
pstree -p | grep apache2
Как узнать PID скрипта
Когда вы запускаете скрипт в оболочке, например Bash запускается процесс известный как подоболочка и выполняет последовательно все команды скрипта. Чтобы узнать PID процесса подоболочки Bash, запущенной для скрипта, обратитесь к специальной переменной $$. Эта переменная доступна только для чтения, поэтому вы не сможете ее редактировать:
#!/bin/bash
echo «PID этого скрипта: $$»
Каким процессом занят файл Linux
Выше мы рассмотрели, как получить PID процесса Linux по имени, а теперь давайте узнаем PID по файлу, который использует процесс. Например, мы хотим удалить какой-либо файл, а система нам сообщает, что он используется другим процессом.
С помощью утилиты lsof можно посмотреть, какие процессы используют директорию или файл в данный момент. Например, откроем аудио-файл в плеере totem, а затем посмотрим, какой процесс использует её файл:
В начале строки мы видим название программы, а дальше идёт её PID. Есть ещё одна утилита, которая позволяет выполнить подобную задачу — это fuser:
Здесь будет выведен только файл и PID процесса. После PID идёт одна буква, которая указывает, что делает этот процесс с файлом или папкой:
- c — текущая директория;
- r — корневая директория;
- f — файл открыт для чтения или записи;
- e — файл выполняется как программа;
- m — файл подключен в качестве библиотеки.
Кто использовал файл в Linux
Узнать процесс, который сейчас занимает файл, достаточно просто. Но как узнать, какой процесс обращается к файлу не надолго, например, выполняет его как программу или читает оттуда данные? Эта задача уже труднее, но вполне решаема с помощью подсистемы ядра auditd. В CentOS набор программ для работы с этой подсистемой поставляется по умолчанию, в Ubuntu же его придётся установить командой:
sudo apt install auditd
Теперь создаём правило для мониторинга. Например, отследим, кто запускает утилиту who:
auditctl -w /usr/bin/who -p x -k who_exec
Здесь -w — адрес файла, который мы будем отслеживать, —p — действие, которое нужно отслеживать, —k — произвольное имя для правила. В качестве действия могут использоваться такие варианты:
- x — выполнение;
- w — запись;
- r — чтение;
- a — изменение атрибутов.
Теперь выполним один раз who и посмотрим, что происходит в логе с помощью команды ausearch:
sudo ausearch -i -k who_exec
Здесь в секции SYSCALL есть PID процесса, под которым была запущена программа, а также PPID — программа, которая запустила нашу who. Копируем этот PID и смотрим информацию о нём с помощью ps:
ps aux | grep 15595
Становиться понятно, что это bash.
Какой процесс использует порт в Linux
Иногда необходимо узнать PID Linux-программы, которая использует сетевой порт, например 80. Для этого можно использовать утилиту ss:
sudo ss -lptn ‘sport = :80’
Мы видим, что это несколько процессов Apache. Использовав опцию dport, можно узнать, какой процесс отправляет данные на указанный порт:
sudo ss -lptn ‘dport = :80’
Выводы
В этой статье мы рассмотрели, как узнать PID процесса в 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:
- Open the terminal window on Linux
- For remote Linux server use the ssh command for log in purpose
- Type the ps aux command to see all running process in Linux
- 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:
- root – User name
- 1 – PID (Linux process ID)
- 19:10 – Process start time
- /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:
Источник