Process name from its pid in linux

61,522

Solution 1

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.

Solution 2

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.

Solution 3

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;
}

Solution 4

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

ps -p 9000 -o comm=

Solution 5

Use the below command in Linux

ls -l /proc/[pid]/exe

It will give the name of the process/application name

Share:
61,522
TheForbidden
Author by

TheForbidden

Updated on December 11, 2020

Comments

  • TheForbidden
    TheForbidden over 3 years

    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?