- How to get current process name in linux?
- 8 Answers 8
- Работа с процессами в Linux
- Список процессов
- Ключи
- Примеры
- Убить процесс
- Подробная информация о процессе
- Потребление ресурсов процессами
- Get the Name of a Process from PID
- 1. Overview
- 2. Introduction to the Problem
- 3. Using the ps Command
- 4. Reading Files Under the /proc/ Directory
- 5. Conclusion
How to get current process name in linux?
How can I get the process name in C? The same name, which is in /proc/$pid/status . I do not want to parse that file. Is there any programmatic way of doing this?
8 Answers 8
If you’re on using a glibc, then:
#define _GNU_SOURCE #include extern char *program_invocation_name; extern char *program_invocation_short_name;
Under most Unices, __progname is also defined by the libc. The sole portable way is to use argv[0]
It’s either pointed to by the argv[0] or indeed you can read /proc/self/status . Or you can use getenv(«_») , not sure who sets that and how reliable it is.
Note that getenv(«_») appears to return the process originally started by the shell — if I call it in a process started by make , I see «/usr/bin/make», rather than my process name. This means that it’s probably set by the shell.
You can use __progname . However it is not better than argv[0] as it may have portability issues. But as you do not have access to argv[0] it can work as follows:-
extern char *__progname; printf("\n%s", __progname);
I often make use of following call,
char* currentprocname = getprogname();
That’s BSD-specific. You can get it on Linux with libbsd , but it’s not part of libc as it is on FreeBSD or OS X.
Look at the value of argv[0] which was passed to main . This should be the name under which your process was invoked.
This is a version that works on macOS, FreeBSD and Linux.
#if defined(__APPLE__) || defined(__FreeBSD__) const char * appname = getprogname(); #elif defined(_GNU_SOURCE) const char * appname = program_invocation_name; #else const char * appname = "?"; #endif
If you cannot access argv[] in main(), because you are implementing a library, you can have a look at my answer on a similar question here.
It basically boils down into giving you access to argc, argv[] and envp[] outside of main(). Then you could, as others have already correctly suggested, use argv[0] to retrieve the process 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 — текущее состояние процесса. Могут принимать значения:
- R — выполнимый процесс;
- S — спящий;
- D — в состоянии подкачки на диске;
- T — остановлен;
- Z — зомби.
- W — не имеет резидентных страниц;
- < —высоко-приоритетный;
- N — низко-приоритетный;
- 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 — команда, которая запустила процесс.
Get the Name of a Process from PID
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
1. Overview
The Linux Operating system generates a PID for each process. In this quick tutorial, let’s explore how to get the process name by a given PID.
2. Introduction to the Problem
As usual, let’s understand the problem by an example.
First, let’s create a simple shell script to simulate a long-running process:
$ cat long-running.sh #!/bin/bash echo "PID of $0: $$" echo "Parameter: $1" watch -n 300 date > /dev/null
As we can see, we first print the PID of the current script by reading the special variable $$. Then, we tell the watch command to execute the date command every 300 seconds and discard the output.
In this way, we can know its PID when we start the script. Further, it runs as a “long-running” process:
$ ./long-running.sh PARAM PID of ./long-running.sh: 407203 parameter: PARAM
Now, assuming we only know this PID, we would like to figure out which process is running with this PID.
Of course, our expected result is the long-running.sh script. Next, let’s see how to find the process.
3. Using the ps Command
The ps command is the standard tool to check current processes’ status in the Linux command line.
Further, we can pass the -p option to the ps command to get only the information of the given process, for example:
$ ps -p 407203 PID TTY TIME CMD 407203 pts/3 00:00:00 long-running.sh
As the output above shows, we’ve seen the expected process name in the CMD column. We can also adjust the ps command’s -o option to ask ps to output only required information.
For example, we can pass “-o comm” to the ps command to get the name of the program only:
$ ps -p 407203 -o comm COMMAND long-running.sh
If we want to know the entire command line that was used to start the given process, we can pass “-o command” to ps:
$ ps -p 407203 -o command COMMAND /bin/bash ./long-running.sh PARAM
As the output shows, this time, the ps command reports the complete command, including parameters used to start the process.
Sometimes, we want to suppress the column header, for example, “COMMAND” in the output above, so that we can easily pass the result to other programs to do further processing.
To suppress the header from the ps output, we can simply add the “=” character after the -o ColumnName option:
$ ps -p 407203 -o command= /bin/bash ./long-running.sh PARAM
4. Reading Files Under the /proc/ Directory
The /proc directory is present on all Linux distributions. This directory is a virtual file system. The /proc directory contains details about processes and other system information such as kernel, memory usage, CPU data, and configuration parameters. The operating system mounts /proc at boot.
Each process has a subdirectory under the /proc directory named with its PID. For example, if we want to check the information of the process 407203, we can enter the /proc/407203 directory. There are many “files” under each /proc/ directory. Those files hold detailed information about the process:
$ ls /proc/407203 arch_status [email protected] maps pagemap stat attr/ environ mem personality statm . [email protected] . cmdline io ns/ sessionid timers comm .
We can read three files to gain the name or the command line of the process: comm, exe, and cmdline. Next, let’s see them in action.
To get the program name of a process, we can read the comm file:
$ cat /proc/407203/comm long-running.sh
The exe file is a symbolic link. It links to the real command file to start the process:
$ ls -l /proc/407203/exe lrwxrwxrwx 1 kent kent 0 Apr 26 09:20 /proc/407203/exe -> /usr/bin/bash
As our process is a shell script, which is always started by the shell, the exe file will merely link to the shell command, which is /usr/bin/bash in this case. However, if our process is started by a regular program, the exe file will point to the executable:
$ ls -l /proc/437301/exe lrwxrwxrwx 1 kent kent 0 Apr 26 09:17 /proc/437301/exe -> /usr/bin/vim
The example above shows a vim process.
However, if we would like to know the complete command that started the process along with its parameters, we can check the cmdline file:
$ cat /proc/407203/cmdline /bin/bash./long-running.shPARAM
As the output above shows, the shell command, script name, and the script parameter are printed, but they are joined together without separators.
Actually, the output is separated by null characters. We can see them if we pass the -A option (display all) to the cat command:
$ cat -A /proc/407203/cmdline /bin/bash^@./long-running.sh^@PARAM^@
This time, we can see that the null characters are represented as ‘^@‘.
We can use the tr command to reformat the output. For example, we can replace all null characters with spaces:
$ cat /proc/407203/cmdline | tr '\0' ' ' /bin/bash ./long-running.sh PARAM
5. Conclusion
In this quick article, we’ve explored how to get the name and the command line of a given PID in the Linux command line.
The ps -p command is pretty straightforward to get the process information of a PID. Alternatively, we can also access the special /proc/PID directory to retrieve process information.