Linux get name from pid

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.

Читайте также:  Что значит сброс сети windows 10

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.

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.

Источник

Process name from its pid in linux

How to get a process name from his pid ? For example I execute cat file1.txt, but I want to figure out that cat command and its arguments since its pid in the system. Is there a struct to determine it or something similar? Any idea?

7 Answers 7

There is not any general way to do this unix.
Each OS has different ways to handle it and some are very hard. You mention Linux though. With Linux, the info is in the /proc filesystem.
To get the command line for process id 9999, read the file /proc/9999/cmdline .

On linux, you can look in /proc/ . Try typing man proc for more information. The contents of /proc/$PID/cmdline will give you the command line that process $PID was run with. There is also /proc/self for examining yourself 🙂

An alternative (e.g. on Mac OS X) is to use libproc . See libproc.h.

POSIX C does NOT support give a standard API for getting the process name by PID.

In linux, you can get the name by LINUX Proc API: /proc/$PID/cmdline. And the code looks like these:

To get the process name of a process id say 9000 use this command:

While this question has been answered, I’d like to add my 2 cents.

In my case, when process 1111 creates process 22222 via pipe (at least this is what I heard), /proc/2222/cmdline does not give correct process name, but instead gives something like 1111_1 . I have to use /proc/2222/comm to get the correct process name.

Use the below command in Linux

It will give the name of the process/application name

Источник

Как узнать PID процесса в Linux

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

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

Как узнать pid процесса Linux

Самый распространённый способ узнать PID Linux — использовать утилиту ps:

Читайте также:  Гибридный спящий режим linux

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:

Читайте также:  Linux convert files to utf8

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 по различным условиям: имени или файлу. Как видите, всё достаточно просто, и в считанные минуты можно можно понять, что происходит с вашей операционной системой, и какой процесс за это отвечает.

Источник

If I know the PID number of a process, how can I get its name?

If I have the PID number for a process (on a UNIX machine), how can I find out the name of its associated process?

What do I have to do?

9 Answers 9

On all POSIX-compliant systems, and with Linux, you can use ps :

Here, the process is selected by its PID with -p . The -o option specifies the output format, comm meaning the command name.

For the full command, not just the name of the program, use:

You can find the process name or the command used by the process-id or pid from

Here pid is the pid for which you want to find the name
For example:

To find the process name used by pid 2480 you use can

To get the path of of the program using a certain pid you can use:

alternatively you can use:

You can use pmap. I am searching for PID 6649. And cutting off the extra process details.

You can Also use awk in combination with ps

to print HEAD LINE you can use

Simmilar to slhck’s Answer, but relying on file operations instead of command invocations:

Surprisingly, no one has mentioned the -f (full command) option for ps. I like to use it with -e (everything) and pipe the results to grep so I can narrow my search.

This is also very useful for looking at full commands that someone is running that are taking a lot of resources on your system. This will show you the options and arguments passed to the command.

I find the easiest method to be with the following command:

Not the answer you’re looking for? Browse other questions tagged linux unix shell process pid or ask your own question.

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.10.8.40416

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Оцените статью