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?

share | improve this question
 
up vote 16 down vote accepted

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.

share | improve this answer
 
5 
And to get the process name for process id 9999, read the file /proc/9999/comm. –  Skippy le Grand Gourou Jul 5 '13 at 15:02

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.

share | improve this answer
 
 
Can you please tell me the difference between your answer and mine? :) –  Anubhab Mar 21 '13 at 11:02
7 
Your answer wasn't there when I started writing mine :) –  robbie_c Mar 21 '13 at 11:02
 
HAHAHA..:D .... –  Anubhab Mar 21 '13 at 11:03
2 
hey don't fight ;) thanks to each one of you –  TheForbidden Mar 21 '13 at 12:54

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值