lyric
lyric

Reputation: 13

linux how to get process params with pid?

When I execute the program ./test -debug 7 -m player,I use C language how to get the parameter values of -m -debug?

I have tried:

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

But it only returns the name of the process.exec "xargs -0 < /proc/pid/cmdline" can return the right value(mytest -debug 7 -m player),I want to get in another process, rather than in the main method of the process.such as,in process mytest2,I want to get mytest process debug value with pid(via pid = getpid() and via pid get mytest process info,and than get debug value ).

Upvotes: 1

Views: 316

Answers (1)

J&#233;r&#244;me Pouiller
J&#233;r&#244;me Pouiller

Reputation: 10257

From proc(5):

The command-line arguments appear in this file as a set of strings separated by null bytes ('\0'), with a further null byte after the last string.

So, this code should work:

for (i = 0; i < size; i++) {
    if (!i)
        printf("%s\n", name);
    else if (!name[i - 1])
        printf("%s\n", name + i);
}

Upvotes: 2

Related Questions