Linux get process name by pid

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 .

The question was how to get the process name, not the commandline. On my SUSE I enter ‘head /proc/9999/cmdline’ for a kwrite process and it returns: ‘kdeinit4: kwrite [kdeinit]’. If I use /comm instead of /cmdline I get the correct result: ‘kwrite’.

@SkippyleGrandGourou /proc//comm will be truncated if it reaches 16 chars or TASK_COMM_LEN, a better way is to read realpath of /proc//exe as shown here

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:

const char* get_process_name_by_pid(const int pid) < char* name = (char*)calloc(1024,sizeof(char)); if(name)< sprintf(name, "/proc/%d/cmdline",pid); FILE* f = fopen(name,"r"); if(f)< size_t size; size = fread(name, sizeof(char), 1024, f); if(size>0) < if('\n'==name[size-1]) name[size-1]='\0'; >fclose(f); > > return name; > 

And if you came here looking for a solution in C# working with mono, then have a look at this: stackoverflow.com/questions/29827331/…

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

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

Каждый раз, когда пользователь или система (Linux) запускает программу, ядро создает процесс. Процесс хранит в памяти детали выполнения программы, такие как входные и выходные данные, переменные и т. д.

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

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

Текущие запущенные процессы в вашей системе, он содержит каталоги для каждого процесса.

Используйте утилиту less для более удобного просмотра содержимого /proc, как показано ниже:

$ ls /proc OR $ ls /proc | less
1 168 2230 25 329 584 7386 83 driver schedstat 10 169 2234 2503 33 603 74 830 execdomains scsi 1070 17 2247 2507 34 610 7411 833 fb self 1081 1702 2256 2523 349 611 7423 836 filesystems slabinfo 109 1714 2258 253 35 612 745 839 fs softirqs 11 173 2266 2551 36 613 746 84 interrupts stat 110 1760 2273 26 362 62 75 844 iomem swaps 1188 1763 2278 2688 3642 63 7533 85 ioports sys 12 1769 2282 2694 3643 64 7589 86 irq sysrq-trigger 1204 177 2283 2695 37 6436 76 860 kallsyms sysvipc 1209 1773 2285 2698 38 65 7619 87 kcore thread-self 1254 18 2287 2699 39 66 7689 9 keys timer_list 13 1847 2295 27 3974 67 7690 94 key-users timer_stats 15 1914 23 2702 3976 68 77 977 kmsg tty 152 1917 2308 28 4273 6897 7725 981 kpagecgroup uptime 153 1918 2309 280 4374 69 7729 987 kpagecount version 154 1938 2310 2815 4392 6969 7733 997 kpageflags version_signature 155 1956 2311 2817 44 6980 78 acpi loadavg vmallocinfo 156 1981 2315 282 45 7 79 asound locks vmstat 1565 1986 2316 283 4543 70 790 buddyinfo mdstat zoneinfo 1567 1988 2317 29 46 71 8 bus meminfo 157 2 2324 2935 461 7102 80 cgroups misc 1579 20 2347 2944 4686 72 808 cmdline modules 158 2010 2354 3 47 73 81 consoles mounts 1584 2043 2436 30 4700 7304 810 cpuinfo mtrr 159 2044 2437 3016 5 7311 815 crypto net 1590 21 2442 31 515 7322 82 devices pagetypeinfo 16 2167 2443 318 5273 7347 820 diskstats partitions 160 22 2492 32 5274 7367 823 dma sched_debug

На снимке экрана выше пронумерованные каталоги хранят информационные файлы о выполняемых процессах, где каждый номер соответствует PID.

Читайте также:  Отключить блокировку экрана linux mint

Ниже приведен список файлов для процесса systemd с PID 1:

ls: cannot read symbolic link '/proc/1/cwd': Permission denied ls: cannot read symbolic link '/proc/1/root': Permission denied ls: cannot read symbolic link '/proc/1/exe': Permission denied attr coredump_filter gid_map mountinfo oom_score schedstat status autogroup cpuset io mounts oom_score_adj sessionid syscall auxv cwd limits mountstats pagemap setgroups task cgroup environ loginuid net personality smaps timers clear_refs exe map_files ns projid_map stack uid_map cmdline fd maps numa_maps root stat wchan comm fdinfo mem oom_adj sched statm

Вы можете использовать команду «взгляд» и многое другое, как показано в примерах ниже:

USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 1 0.0 0.0 185728 6268 ? Ss 10:15 0:01 /sbin/init splash root 2 0.0 0.0 0 0 ? S 10:15 0:00 [kthreadd] root 3 0.0 0.0 0 0 ? S 10:15 0:00 [ksoftirqd/0] root 5 0.0 0.0 0 0 ? S< 10:15 0:00 [kworker/0:0H] root 7 0.0 0.0 0 0 ? S 10:15 0:09 [rcu_sched] root 8 0.0 0.0 0 0 ? S 10:15 0:00 [rcu_bh] root 9 0.0 0.0 0 0 ? S 10:15 0:00 [migration/0] root 10 0.0 0.0 0 0 ? S 10:15 0:00 [watchdog/0] root 11 0.0 0.0 0 0 ? S 10:15 0:00 [watchdog/1] root 12 0.0 0.0 0 0 ? S 10:15 0:00 [migration/1] root 13 0.0 0.0 0 0 ? S 10:15 0:00 [ksoftirqd/1] root 15 0.0 0.0 0 0 ? S< 10:15 0:00 [kworker/1:0H] root 16 0.0 0.0 0 0 ? S 10:15 0:00 [watchdog/2] root 17 0.0 0.0 0 0 ? S 10:15 0:00 [migration/2] root 18 0.0 0.0 0 0 ? S 10:15 0:00 [ksoftirqd/2] root 20 0.0 0.0 0 0 ? S< 10:15 0:00 [kworker/2:0H] root 21 0.0 0.0 0 0 ? S 10:15 0:00 [watchdog/3] root 22 0.0 0.0 0 0 ? S 10:15 0:00 [migration/3] root 23 0.0 0.0 0 0 ? S 10:15 0:00 [ksoftirqd/3] root 25 0.0 0.0 0 0 ? S< 10:15 0:00 [kworker/3:0H] root 26 0.0 0.0 0 0 ? S 10:15 0:00 [kdevtmpfs] root 27 0.0 0.0 0 0 ? S< 10:15 0:00 [netns] root 28 0.0 0.0 0 0 ? S< 10:15 0:00 [perf] .

Отслеживайте процессы Linux с помощью традиционной команды top.

Читайте также:  Linux permissions write only

Отслеживайте процессы Linux с помощью glances, нового инструмента мониторинга процессов в Linux в режиме реального времени.

Узнайте больше о том, как установить Glances в системах Linux.

Узнать номер PID процесса

Чтобы узнать PID процесса, вы можете использовать pidof , простую команду для вывода PID процесса:

$ pidof firefox $ pidof python $ pidof cinnamon

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

Узнать имя процесса по номеру PID

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

$ ps -p 2523 -o comm= $ ps -p 2295 -o comm=

Для получения дополнительной информации об использовании и параметрах просмотрите справочную страницу ps.

Если вы хотите убить процесс, используя его номер PID, я предлагаю вам прочитать Поиск и уничтожение процессов Linux с использованием его PID.

На данный момент это все, если вы знаете какой-либо другой лучший способ узнать имя процесса с помощью 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:

$ ls /proc OR $ ls /proc | less
1 168 2230 25 329 584 7386 83 driver schedstat 10 169 2234 2503 33 603 74 830 execdomains scsi 1070 17 2247 2507 34 610 7411 833 fb self 1081 1702 2256 2523 349 611 7423 836 filesystems slabinfo 109 1714 2258 253 35 612 745 839 fs softirqs 11 173 2266 2551 36 613 746 84 interrupts stat 110 1760 2273 26 362 62 75 844 iomem swaps 1188 1763 2278 2688 3642 63 7533 85 ioports sys 12 1769 2282 2694 3643 64 7589 86 irq sysrq-trigger 1204 177 2283 2695 37 6436 76 860 kallsyms sysvipc 1209 1773 2285 2698 38 65 7619 87 kcore thread-self 1254 18 2287 2699 39 66 7689 9 keys timer_list 13 1847 2295 27 3974 67 7690 94 key-users timer_stats 15 1914 23 2702 3976 68 77 977 kmsg tty 152 1917 2308 28 4273 6897 7725 981 kpagecgroup uptime 153 1918 2309 280 4374 69 7729 987 kpagecount version 154 1938 2310 2815 4392 6969 7733 997 kpageflags version_signature 155 1956 2311 2817 44 6980 78 acpi loadavg vmallocinfo 156 1981 2315 282 45 7 79 asound locks vmstat 1565 1986 2316 283 4543 70 790 buddyinfo mdstat zoneinfo 1567 1988 2317 29 46 71 8 bus meminfo 157 2 2324 2935 461 7102 80 cgroups misc 1579 20 2347 2944 4686 72 808 cmdline modules 158 2010 2354 3 47 73 81 consoles mounts 1584 2043 2436 30 4700 7304 810 cpuinfo mtrr 159 2044 2437 3016 5 7311 815 crypto net 1590 21 2442 31 515 7322 82 devices pagetypeinfo 16 2167 2443 318 5273 7347 820 diskstats partitions 160 22 2492 32 5274 7367 823 dma sched_debug

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

Читайте также:  How to run linux command in windows

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

ls: cannot read symbolic link '/proc/1/cwd': Permission denied ls: cannot read symbolic link '/proc/1/root': Permission denied ls: cannot read symbolic link '/proc/1/exe': Permission denied attr coredump_filter gid_map mountinfo oom_score schedstat status autogroup cpuset io mounts oom_score_adj sessionid syscall auxv cwd limits mountstats pagemap setgroups task cgroup environ loginuid net personality smaps timers clear_refs exe map_files ns projid_map stack uid_map cmdline fd maps numa_maps root stat wchan comm fdinfo mem oom_adj sched statm

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:

USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 1 0.0 0.0 185728 6268 ? Ss 10:15 0:01 /sbin/init splash root 2 0.0 0.0 0 0 ? S 10:15 0:00 [kthreadd] root 3 0.0 0.0 0 0 ? S 10:15 0:00 [ksoftirqd/0] root 5 0.0 0.0 0 0 ? S< 10:15 0:00 [kworker/0:0H] root 7 0.0 0.0 0 0 ? S 10:15 0:09 [rcu_sched] root 8 0.0 0.0 0 0 ? S 10:15 0:00 [rcu_bh] root 9 0.0 0.0 0 0 ? S 10:15 0:00 [migration/0] root 10 0.0 0.0 0 0 ? S 10:15 0:00 [watchdog/0] root 11 0.0 0.0 0 0 ? S 10:15 0:00 [watchdog/1] root 12 0.0 0.0 0 0 ? S 10:15 0:00 [migration/1] root 13 0.0 0.0 0 0 ? S 10:15 0:00 [ksoftirqd/1] root 15 0.0 0.0 0 0 ? S< 10:15 0:00 [kworker/1:0H] root 16 0.0 0.0 0 0 ? S 10:15 0:00 [watchdog/2] root 17 0.0 0.0 0 0 ? S 10:15 0:00 [migration/2] root 18 0.0 0.0 0 0 ? S 10:15 0:00 [ksoftirqd/2] root 20 0.0 0.0 0 0 ? S< 10:15 0:00 [kworker/2:0H] root 21 0.0 0.0 0 0 ? S 10:15 0:00 [watchdog/3] root 22 0.0 0.0 0 0 ? S 10:15 0:00 [migration/3] root 23 0.0 0.0 0 0 ? S 10:15 0:00 [ksoftirqd/3] root 25 0.0 0.0 0 0 ? S< 10:15 0:00 [kworker/3:0H] root 26 0.0 0.0 0 0 ? S 10:15 0:00 [kdevtmpfs] root 27 0.0 0.0 0 0 ? S< 10:15 0:00 [netns] root 28 0.0 0.0 0 0 ? S< 10:15 0:00 [perf] .

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:

$ pidof firefox $ pidof python $ pidof cinnamon

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:

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.

$ ps -p 2523 -o comm= $ ps -p 2295 -o comm=

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.

Источник

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