Linux узнать pid пользователя

How to find PID’s user name in Linux?

Can you help me to find the PID’s user name? Sometimes my server has high load. When I run top -c , I cannot even find the owner of a process which is causing load on the server.

We were experiencing server load issue due to bulk php process, so that i had this question, we can then find them using ‘lsof -p xxxx’.

6 Answers 6

I’m surprised nobody has put this up yet:

Try the -p option of the ps command.

For instance, if you have PID 1234 , run:

The -u was added to include the username in the output.

You can then use grep or awk , etc. to extract the info you want.

You were a tick faster than me. You’re waking up earlier? Depending on the Linux distrbution, ps u 1234 (Debian) or just ps 1234 (Android with Busybox) also works.

This works nicely with pgrep when you only have the process name (not the PID) or when you want to see the owners of multiple processes with a similar name: ps -u -p $(pgrep yourProcessName)

/proc/processID/status will have the information about user’s ID which you can use to find the username.

uid=$(awk '/^Uid:/' /proc/YOUR_PROCESS_ID/status) getent passwd "$uid" | awk -F: '' 

Replace YOUR_PROCESS_ID with your process ID number.

The best answer, since it’s the fastest, especially if changed to : getent passwd $(< /proc/"$uid"/loginuid) | sed 's/\:.*$//'

Get only username from a PID:

PID=136323 USERNAME="$( ps -o uname= -p "$" )" 

You can also combine it with a pgrep . In this example we show all usernames executing some .php file:

pgrep -f '\.php' | xargs -r ps -o uname= -p | sort -u 

Find only one username running a certain unique process:

USERNAME mt24"> 
)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter " data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f4.0%2f" data-se-share-sheet-license-name="CC BY-SA 4.0" data-s-popover-placement="bottom-start">Share
)" title="">Improve this answer
)">edited Sep 25, 2018 at 0:30
answered Sep 25, 2018 at 0:21
Add a comment |
3

I think the shortest way is:

id -nu 

The /proc//loginuid file has the uid number of the user running the process; id -nu reads uid from stdin and returns a user name.

Источник

Работа с процессами в Linux

Обновлено

Обновлено: 29.03.2023 Опубликовано: 09.11.2017

Список процессов

USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 661 0.0 0.0 4072 8 tty1 Ss+ Jul03 0:00 /sbin/mingetty
root 662 0.0 0.0 4072 8 tty2 Ss+ Jul03 0:00 /sbin/mingetty
root 16355 0.0 0.0 171636 3308 pts/0 S 15:46 0:00 sudo su
root 16366 0.0 0.0 140896 1556 pts/0 S 15:46 0:00 su
root 16368 0.0 0.0 108316 1944 pts/0 S 15:46 0:00 bash
root 18830 0.0 0.0 110244 1172 pts/0 R+ 16:20 0:00 ps u

  • USER — учетная запись пользователя, от которой запущен процесс.
  • PID — идентификатор процесса.
  • %CPU — потребление процессорного времени в процентном эквиваленте.
  • %MEM — использование памяти в процентах.
  • VSZ — Virtual Set Size. Виртуальный размер процесса (в килобайтах).
  • RSS — Resident Set Size. Размер резидентного набора (количество 1K-страниц в памяти).
  • TTY — терминал, из под которого был запущен процесс.
  • STAT — текущее состояние процесса. Могут принимать значения:
    1. R — выполнимый процесс;
    2. S — спящий;
    3. D — в состоянии подкачки на диске;
    4. T — остановлен;
    5. Z — зомби.
    6. W — не имеет резидентных страниц;
    7. < —высоко-приоритетный;
    8. N — низко-приоритетный;
    9. L — имеет страницы, заблокированные в памяти.
  • START — дата запуска процесса.
  • TIME — время запуска процесса.
  • COMMAND — команда, запустившая процесс.

Ключи

Ключ Описание
-A Все процессы.
-a Запущенные в текущем терминале, кроме главных системных.
-d Все, кроме главных системных процессов сеанса.
-e Все процессы.
f Показать дерево процессов с родителями.
T Все на конкретном терминале.
a Все, связанные с текущим терминалом и терминалами других пользователей.
r Список только работающих процессов.
x Отсоединённые от терминала.
u Показать пользователей, запустивших процесс.

Примеры

Поиск процесса с помощью grep:

Убить процесс

Останавливаем процесс по его PID:

Если процесс не завершается, убиваем его принудительно:

Остановить все процессы с именем nginx:

Как и в случае с kill, можно это сделать принудительно:

Можно остановить все процессы конкретного пользователя:

Ищем процесс по имени, извлекаем его PID и завершаем его:

kill `ps aux | grep 'apache' | awk ''`

* обратите внимание, что запрос может вывести несколько процессов, которые будут попадать под критерии поиска — в таком случае, они будут завершены все.

Подробная информация о процессе

Для каждого процесса создается каталог по пути /proc/ , в котором создаются папки и файлы с описанием процесса.

Примеры использования /proc/

Адрес в ячейках оперативной памяти, которые занял процесс:

Команда, которой был запущен процесс:

Символьная ссылка на рабочий каталог процесса:

Символьная ссылка на исполняемый файл, запустивший процесс:

Увидеть ссылки на дескрипторы открытых файлов, которые затрагивает процесс:

Подробное описание на сайте man7.org.

Потребление ресурсов процессами

Для просмотра статистики потребления ресурсов используем утилиту top:

PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
21059 root 20 0 157884 2280 1496 R 18,8 0,1 0:00.03 top
1 root 20 0 190996 2964 1652 S 0,0 0,1 6:49.99 systemd
2 root 20 0 0 0 0 S 0,0 0,0 0:01.78 kthreadd
3 root 20 0 0 0 0 S 0,0 0,0 0:24.75 ksoftirqd/0
5 root 0 -20 0 0 0 S 0,0 0,0 0:00.00 kworker/0:0H

  • PID — идентификатор процесса.
  • USER — имя учетной записи, от которой запущен процесс.
  • PR — приоритет процесса.
  • NI — приоритет, выставленной командой nice.
  • VIRT — объем виртуальной памяти, потребляемый процессом.
  • RES — объем используемой оперативной памяти.
  • SHR — количество разделяемой памяти, которое используется процессом.
  • S — состояние процесса.
  • %CPU — процент использования процессорного времени.
  • %MEM — потребление оперативной памяти в процентах.
  • TIME — использование процессорного времени в секундах.
  • COMMAND — команда, которая запустила процесс.

Источник

How to get UID and PID

So here's what I want to do: User inputs a USERNAME. Based on this username, I need to get the list of processes started by this user. I am planning to do this by getting the UID of this user and listing all the processes with this UID. I only found UID in the /proc/$PID/status file. I am unclear about how do I proceed with this.

I want to get the UID of the user. Once UID is available, I need to fetch all the PIDs that are under this UID (Basically, get all the processes started by this user). pgrep lists all the PIDs of a particular user, but I need the UID too.

1 Answer 1

To get the UID from the username, use id -u :

$ id -u root 0 $ id -u lightdm 112 $ id -u nobody 65534 

But you are re-inventing the wheel. pgrep already handles this just fine:

$ pgrep -u www-data 1909 1910 1911 1912 $ id -u www-data 33 $ pgrep -u 33 1909 1910 1911 1912 

You can also use plain ps :

$ ps -U www-data -o uid,pid UID PID 33 1909 33 1910 33 1911 33 1912 

You must log in to answer this question.

Linked

Hot Network Questions

Subscribe to RSS

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

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.17.43536

Linux is a registered trademark of Linus Torvalds. UNIX is a registered trademark of The Open Group.
This site is not affiliated with Linus Torvalds or The Open Group in any way.

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

Источник

How to Find the PID and PPID of a Process in Linux

Knowing the PID and PPID of a process can be helpful if you need to manage or interact with a process running on your system.

There are numerous ways to get the PID (Process ID) and PPID (Parent Process ID) of a given process in Linux.

Command Description
pidof process_name Works with exact process name
pgrep process_name Returns PID of all matches
ps -o ppid= -p PID Get the PPID from PID
$$ PID of current process/shell
$ PID of current process's parent

I'll explain these commands in detail but before that a quick recap of process, PID and PPID.

Linux process basics

Everything that runs on your system is ran via something known as a process, with that simply being the running instance of a program.

All the processes that run on your system are assigned identifiers. These can be helpful if you want to monitor the process (for example, such as to see how much memory or CPU it is using), or maybe if you want to end it if it starts to hang or just act a bit funky.

The identifiers that get attached to all these processes are known as PIDs and PPIDs.

What is a PID?

PID stands for "process ID". Again, this is simply the identifier that gets attached to a program when it starts running, and can be helpful if you need to interact with the process in one way or another.

What is a PPID?

PPID is quite closely related to a PID. PPID stands for "parent process ID", and if you didn't get it already, it simply stands for the process that created the process you are checking.

For example, let's say that we have two processes. One is named "spawner", and has a process ID (or PID) of 7234. Our second process, "email client", has a process ID of 7456 when we create it. Our spawner program starts our email client, resulting in our email client having a PID of 7456, and a PPID of 7234, since the spawner (which had the PID of 7234) is what spawned the email client.

Now that you have brushed up your basic, let's see how to get the process ID in Linux.

Getting the PID of a process

The important thing here is to know the name of the process whose PID you want to find.

If you know the exact process name, you can get its process ID using the pidof command:

Easier said than done because you may not always know the exact process name. Good thing here is that pidof command works with tab completion so if you know the starting few letters of the process name, you can hit tab to get matching suggestions.

Example of pidof command which is used for finding PID of a process in Linux

However, that may not always work if the process name doesn't match to what you think it is called. For example, the process for Edge browser on Linux is called msedge . It doesn't start with 'edge' and the tab completion won't work if you focus on 'edge'.

So, what you can do is to resort to the ps command in Linux to list all the running processes from all users and then use grep on the output to filter the result.

ps aux | grep -i partial_process_name

There is a dedicated command that combines the features ps and grep command and it is unsurprisingly called pgrep:

pgrep partial_or_exact_process_name

pgrep command

The default output shows only the PIDs without any information on the process. This could be troublesome if there is more than one process IDs returned for your searched term.

Hence, I suggest using the listing feature to make sure that you are getting the PID of the desired process.

pgrep -l partial_or_exact_process_name

pgrep command example

You may also use the top command to get the process information but it cannot be used in scripts.

You can use the pstree command to get the PIDs of all running process on your Linux system: pstree -p -a

Getting PPID from a child process's PID

Once you know the PID of a process, it is effortless to find the PPID for that process.

You can simply run the following command, replacing PID with the current process (child) ID:

In a shell, the above command and $ should both return the same output:

And that's about everything there is to finding PIDs and PPIDs!

Checking the PID and PPID of the currently running process

If you're in a shell such as Bash, it's extremely easy to find the PID and PPID of the calling process (which will usually be the shell).

Bash stores the PID's value under the $$ variable, and the PPID under the $ variable:

PID and PPID of current shell

And it's that easy! Finding the PIDs and PPIDs of other processes isn't much harder either.

Wrapping up

You should now know everything you need to find both PIDs and PPIDs for running processes on your system.

If you need any help getting something working, or just got some remaining questions, feel free to leave that and anything else in the comments below.

Источник

Читайте также:  About system kali linux
Оцените статью
Adblock
detector