gpt4 book ai didi

c - linux如何使用pid获取进程参数?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:11:41 26 4
gpt4 key购买 nike

我用C语言执行程序./test -debug 7 -m player时,如何获取-m -debug的参数值?

我试过:

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

但它只返回进程的名称。exec "xargs -0

最佳答案

来自 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.

所以,这段代码应该可以工作:

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

关于c - linux如何使用pid获取进程参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35840847/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com