Find pid in linux

How to Find a Process Name Using PID Number in Linux

In this article, we will look at how to find a process name by its process identification number (PID). Before we dive into the actual solution, let us briefly talk about how processes are created and identified by Linux.

Every time a user or the system (Linux) launches a program, the kernel will create a process. A process holds execution details of the program in memory such as its input and output data, variables and so on.

Importantly, since Linux is a multitasking operating system, it executes several programs simultaneously, and this means each process process must be identified specifically.

The kernel identifies each process using a process ID (PID), a every instance of process must have a unique PID from other processes which is assigned when the process is invoked, to avoid any execution errors.

The /proc file system stores information about currently running processes on your system, it contains directories for each process.

Use the ls command to list its contents, however, the list may be long, so employ a pipeline and the less utility to view the /proc contents in a more convenient way as below:

From the screenshot above, the numbered directories store information files about the processes in execution, where each number corresponds to a PID.

Below is the list of files for systemd process with PID 1:

You can monitor processes and their PIDs using traditional Linux commands such as ps, top and relatively new glances command plus many more as in the examples below:

Monitor Linux processes using traditional top command.

Monitor Linux Processes with top Command

Monitor Linux processes using glances, a new real-time process monitoring tool for Linux.

Glances – Real Time Linux Processes Monitoring

Find Out Process PID Number

To find out the PID of a process, you can use pidof , a simple command to print out the PID of a process:

Find Linux Process PID

Coming back to our point of focus, assuming you already know the PID of a process, you can print its name using the command form below:

  1. -p specifies the PID
  2. -o format enables a user-defined format

Find Out Process Name Using PID Number

In this section, we will see how to find out a process name using its PID number with the help of user defined format i.e comm= which means command name, same as the process name.

Find Linux Process Name

For additional usage information and options, look through the ps man page.

If you want to kill a process using its PID number, I suggest you to read Find and Kill Linux Processes Using its PID.

Читайте также:  Tcpdump для windows пример

Thats it for the moment, if you know any other better way to find out a process name using PID, do share with us via our comment section below.

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.

Источник

9 самых простых способов узнать идентификатор процесса (PID) в Linux

В основном, мы смотрим PID, чтобы убить невосприимчивую программу, и она похожа на диспетчер задач Windows.

Linux GUI также предлагает ту же функцию, но CLI – эффективный способ выполнения операции kill.

Что такое идентификатор процесса PID?

PID обозначает идентификационный номер процесса, который обычно используется большинством ядер операционной системы, таких как Linux, Unix, macOS и Windows.

Это уникальный идентификационный номер, который автоматически присваивается каждому процессу, когда он создается в операционной системе.

Процесс – это исполняемый экземпляр программы.

PID для запущенных процессов в системе можно найти с помощью следующих девяти методов, таких как команда pidof, команда pgrep, команда ps, команда pstree, команда ss, команда netstat, команда lsof, команда fuser и команда systemctl.

  • pidof: pidof – найти идентификатор процесса запущенной программы.
  • pgrep: pgre – поиск или обработка сигналов на основе имени и других атрибутов.
  • ps: ps – сообщает моментальный снимок текущих процессов.
  • pstree: pstree – отображает дерево процессов.
  • ss: ss используется для вывода статистики сокетов.
  • netstat: netstat отображает список открытых сокетов.
  • lsof: lsof – список открытых файлов.
  • fuser: идентификаторы процессов в списке терминов всех процессов, которые открывают один или несколько файлов
  • systemctl: systemctl – Управление системой systemd и менеджером сервисов

В этом уроке мы рассмотрим идентификатор процесса Apache для проверки.

Метод-1: Использование команды pidof

pidof используется для поиска идентификатора процесса запущенной программы.

Он выводит эти идентификаторы на стандартный вывод.

Чтобы продемонстрировать это, мы узнаем идентификатор процесса Apache2 из системы Debian 9.

Из вышесказанного вы можете столкнуться с трудностями идентификации идентификатора процесса, поскольку он показывает все PID (включая родительский и дочерний) с именем процесса.

Следовательно, нам нужно выяснить родительский PID (PPID), который мы ищем.

Это может быть первый номер. В моем случае это 3754, и он показан в порядке убывания.

Способ-2: Использование команды pgrep

pgrep просматривает текущие процессы и перечисляет идентификаторы процессов, которые соответствуют критериям выбора для stdout.

Это также похоже на вышеприведенный вывод, но этот приводит к сокращению результатов в порядке возрастания, что ясно говорит о том, что родительский PID является последним.

В моем случае это 3754.

Примечание. Если у вас есть несколько идентификаторов процесса, вы можете столкнуться с проблемой идентификации идентификатора родительского процесса при использовании команды pidof & pgrep.

Метод-3: Использование команды pstree

pstree показывает запущенные процессы как дерево.

Дерево коренится либо в pid, либо в init, если pid опущен.

Если имя пользователя указано в команде pstree, тогда отображается весь процесс, принадлежащий соответствующему пользователю.

pstree визуально объединяет идентичные ветви, помещая их в квадратные скобки и префикс с количеством повторений.

Чтобы получить только один родительский процесс, используйте следующий формат.

Команда pstree очень простая, потому что она отдельно разделяет родительский и дочерний процессы

Метод-4: Использование команды ps

ps отображает информацию о выборе активных процессов.

Он отображает идентификатор процесса (pid = PID), терминал, связанный с процессом (tname = TTY), кумулятивное время процессора в формате [DD-] hh: mm: ss (time = TIME) и исполняемое имя (ucmd = ЦМД).

По умолчанию выходной файл не сортируется.

Читайте также:  Serial library c windows

Из вышеприведенного вывода мы можем легко идентифицировать идентификатор родительского процесса (PPID) на основе даты начала процесса.

В моем случае процесс apache2 был запущен @ Dec11, который является родителем, а другие – дочерними. PID apache2 равен 3754.

Метод-5: Использование команды ss

ss используется для вывода статистики сокетов.

Он позволяет отображать информацию, аналогичную netstat.

Он может отображать больше информации о TCP и состоянии, нежели другие инструменты.

Он может отображать статистику для всех типов сокетов, таких как PACKET, TCP, UDP, DCCP, RAW, домен Unix и т. д.

Метод-6: Использование команды netstat

netstat – вывод сетевых подключений, таблиц маршрутизации, статистики интерфейсов, соединений маскарадинга и многоадресной рассылки.

По умолчанию netstat отображает список открытых сокетов.

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

Эта программа устарела. Замена для netstat – ss.

Метод-7: использование команды lsof

lsof – список открытых файлов.

Команда lsof Linux выводит информацию о файлах, открытых для процессов, запущенных в системе.

Метод-8: Использование команды fuser

Утилита fuser должна записывать на стандартный вывод идентификаторы процессов процессов, запущенных в локальной системе, которые открывают один или несколько именованных файлов.

Метод-9: Использование команды systemctl

systemctl – Управление системой systemd и менеджером сервисов.

Это замена старого системного управления SysV и большинство современных операционных систем Linux были адаптированы systemd.

Источник

Linux / UNIX: Find out or determine if process pid is running

H ow do I find out my process is running on a Unix-like operating systems? How do I get the pid number for particular process on a Linux operating systems using bash shell?

A PID is an acronym for process identification number on a Linux or Unix-like operating system. A PID is automatically assigned to each process when it is created. A process is nothing but running instance of a program and each process has a unique PID on a Unix-like system.[donotprint]

Tutorial details
Difficulty level Easy
Root privileges No
Requirements None
Est. reading time 2m

[/donotprint]

The easiest way to find out if process is running is run ps aux command and grep process name. If you got output along with process name/pid, your process is running.

Task: Find out process pid

Simply use ps command as follows:
ps aux | grep

For example find out if mysqld process (mysqld pid) is running or not:
$ ps aux | grep mysqld
Sample outputs:

  • 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

Find the process ID of a running program using pidof

pidof command finds the process id’s (pids) of the named programs. It prints those id’s on screen. This program is on some systems used in run level change scripts, especially when the system has a System-V like rc structure. In that case these scripts are located in /etc/rc?.d, where ? is the runlevel. If the system has a start-stop-daemon (8) program that should be used instead.
# pidof mysqld
Sample outputs:

Find PID using pgrep command

The pgrep command searches the running system and shows the process IDs of all processes that match the given criteria. The syntax is:
pgrep pgrep firefox
pgrep httpd
pgrep nginx
Sample outputs:

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

Linux pidof Command Examples To Find PID of A Program/Command

I am a new Linux system user and I using CentOS Linux on server. How can I find the process ID (PID) of a running program on Linux based system using shell prompt?

A PID is an acronym for process identification number on Linux or Unix-like systems. It is nothing but an identification number that is automatically assigned to each process when it is created.

pidof command details
Description Get the process ID of arunning program
Category Processes Management
Difficulty Easy
Root privileges No
Est. reading time 3 mintues
Table of contents
  • » Syntax
  • » Examples
  • » Get only one pid
  • » Get pids of scripts
  • » Omit processes
  • » Find pid of a program and kill it
  • » Options
  • » See also

Purpose

Find the process ID of a running program by name on Linux.

Syntax

The basic syntax is as follows:

  • 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

pidof [options] program1 program2 . programN

NOTE: You may need to run this program as root user to find and kill pid of privileged programs.

pidof command examples

To find pid of lighttpd process, enter:
$ pidof lighttpd
Sample outputs:

Fig. 01: pidof command in action

Get only one pid of a program named php5-cgi

By default pidof displays all pids of named command/program:
$ pidof php5-cgi
Sample outputs (see fig.01):

To display only one pid of the program pass the -s option as follows:
$ pidof -s php5-cgi
Sample outputs (see fig.01):

Get pids of scripts

The pidof command will not display pids of shell/perl/python scripts. To find the process id’s of shells running the named script called featch-data, pass the -x option:
$ pidof -x fetch-data

Omit processes

You can ask pidof commmand to ignore or omit processes with that process id. This is useful to ignore calling shell or shell script or specific pid. In this example, find all pids of lighttpd but omit pid # 4242:
# pidof -o 4242 lighttpd
You can use the special pid %PPID to name the parent process of the pidof program in shell scripts:

Find pid of a program and kill it

In this example, find all PIDs of nginx server and kill it:

Find pids of firefox and kill it focefully as the browser has stuck/frozen using kill command

pidof command options

From the pidof(8) command man page:

Option Description
-s Find only one pid i.e. single shot.
-c Only return process ids that are running with the same root directory. This option is ignored for non-root users, as they will be unable to check the current root directory of processes they do not own.
-n Avoid stat(2) system function call on all binaries which are located on network based file systems like NFS.
-x Find pid for scripts too.
-o Tells pidof to omit processes with that process id.
See also
  • pidof(8) Linux/Unix command man page

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

Читайте также:  Как вызвать окно восстановления windows 10 через биос
Оцените статью