TheForbidden
TheForbidden

Reputation: 1573

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?

Upvotes: 36

Views: 74548

Answers (7)

inihsrah
inihsrah

Reputation: 11

ps --pid <pid> -o comm h : This command gives executable file name. For example if you run a script name.sh, then the above command gives output as bash

ps --ppid <pid> -o comm h: This command gives the output as name

Upvotes: 1

Vikram B
Vikram B

Reputation: 137

Use the below command in Linux

ls -l /proc/[pid]/exe

It will give the name of the process/application name

Upvotes: 3

toddwz
toddwz

Reputation: 541

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.

Upvotes: 3

Thunder
Thunder

Reputation: 3064

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

ps -p 9000 -o comm=

Upvotes: 14

QJGui
QJGui

Reputation: 967

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

Upvotes: 15

robbie_c
robbie_c

Reputation: 2458

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.

Upvotes: 16

Anubhab
Anubhab

Reputation: 1786

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.

Upvotes: 30

Related Questions