Ich versuche,/proc/[pid]/stat in Ubuntu UNIX.Aber die Ausgabe kommt als Segmentierung Fehler. Ich gebe pid an get_usage() weiter.Nicht lesen/proc/[pid]/stat in Unix zeigt Segmentierung Fehler
#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;
}
Ausgang:
Segmentation fault(core dumped)
-Code Quelle: https://github.com/fho/code_snippets/blob/master/c/getusage.c
spezifizieren Sie Ihre Ausgabe und wo Sie einen Fehler erhalten genau – greenshade
Ihr Bemühen, 'strncat' als sicheren Ersatz für' strcat' zu verwenden, ist anerkennenswert, macht aber Ihren Code sehr schwer zu lesen. Sie sind hier ziemlich sicher, weil Ihre Eingabewerte in diesem Fall gut bekannt sind. Der Code weist keine offensichtlichen Fehler auf. Sind Sie sicher, dass Sie tatsächlich einen Zeiger auf ein korrekt zugeordnetes 'struct pstat' als 'Ergebnis' übergeben? – tofro
Eigentlich führe ich gerade so viel Code aus und speichere das Ergebnis nicht. Weil ich mit diesem Code nicht öffnen kann/proc/[pid]/stat Datei – Vipin