linux文件/proc下的进程信息中,有一个cmdline文件,该文件中保持了本进程的执行命令,但是该文件中的命令比较有意思的是,当启动进程时含有参数时,会在各个参数中使用 字符'\0'进行分割,所以如何直接打印该命令,只能打印出第一个参数,即进程名,如果想打印全部参数,需要把各个参数的'\0'字符转为空格,就可以打印了。
可以使用如下函数得到该命令
int get_command(pid_t pid, char *command)
{
int ret;
int i;
int len;
FILE *fp;
char filepath[256];
sprintf(filepath, "/proc/%d/cmdline", pid);
fp = fopen(filepath, "r");
if(fp == NULL)
{
printf("fopen error!\n");
return -1;
}
ret = fscanf(fp, "%s", command);
if(ret == -1)
{
printf("fscanf error\n");
return -1;
}
printf("command = %s\n", command);
len = ftell(fp);
for(i = 0; i < len; ++i)
{
printf("command[%d] = %d\n", i, command[i]);
if(command[i] == 0)
command[i] = ' ';
}
command[len] = 0;
printf("command = %s\n", command);
fclose(fp);
return 1;
}