无法在unix中读取/ proc / [pid] / stat显示分段错误

时间:2016-03-26 12:16:07

标签: c linux unix

我试图在ubuntu UNIX中读取/ proc / [pid] / stat。但输出是分段错误。我正在将pid传递给get_usage()。

 #include <stdlib.h> 
 #include <sys/types.h>
 #include <stdio.h>
 #include <string.h>
 #include <unistd.h>

struct pstat {
long unsigned int utime_ticks;
long int cutime_ticks;
long unsigned int stime_ticks;
long int cstime_ticks;
long unsigned int vsize; // virtual memory size in bytes
long unsigned int rss; //Resident  Set  Size in bytes

long unsigned int cpu_total_time;
 };

 void main(){
  int pid_t; 
  struct pstat *result;
  pid_t = getpid();
  get_usage(pid_t,result);
   }
 int get_usage(const pid_t pid, struct pstat* result) {

printf("%d",pid);
char pid_s[20];
snprintf(pid_s, sizeof(pid_s), "%d", pid);
char stat_filepath[30] = "/proc/"; 

strncat(stat_filepath, pid_s,sizeof(stat_filepath) - strlen(stat_filepath) -1);

strncat(stat_filepath, "/stat", sizeof(stat_filepath) -strlen(stat_filepath) -1);
printf("%s",stat_filepath);

FILE *fpstat = fopen(stat_filepath, "r");

if (fpstat == NULL) {
    perror("FOPEN ERROR ");
    return -1;
}

FILE *fstat = fopen("/proc/stat", "r");
if (fstat == NULL) {
    perror("FOPEN ERROR ");
    fclose(fstat);
    return -1;
}


//read values from /proc/pid/stat
bzero(result, sizeof(struct pstat));
long int rss;
if (fscanf(fpstat, "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %lu"
            "%lu %ld %ld %*d %*d %*d %*d %*u %lu %ld",
            &result->utime_ticks, &result->stime_ticks,
            &result->cutime_ticks, &result->cstime_ticks, &result->vsize,
            &rss) == EOF) {
    fclose(fpstat);
    return -1;
}
fclose(fpstat);
result->rss = rss * getpagesize();

//read+calc cpu total time from /proc/stat
long unsigned int cpu_time[10];
bzero(cpu_time, sizeof(cpu_time));
if (fscanf(fstat, "%*s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
            &cpu_time[0], &cpu_time[1], &cpu_time[2], &cpu_time[3],
            &cpu_time[4], &cpu_time[5], &cpu_time[6], &cpu_time[7],
            &cpu_time[8], &cpu_time[9]) == EOF) {
    fclose(fstat);
    return -1;
}

fclose(fstat);

for(int i=0; i < 10;i++)
    result->cpu_total_time += cpu_time[i];

return 0;
  }

输出:

    Segmentation fault(core dumped)

代码来源:https://github.com/fho/code_snippets/blob/master/c/getusage.c

1 个答案:

答案 0 :(得分:2)

get_usage()中,您正在调用bzero(),然后尝试fscanf()使用名为result的变量,该变量从未分配过内存。

您需要将main()函数中的结果变量设为struct stat result并将&result传递给get_usage()函数。