I am trying to write a script that has a function to get process details.
So far I have
#include <stdio.h>
#include <string.h>
#include <ctype.h>
char* getField(FILE* file, char* prop, int len){
char line[100], *p;
while(fgets(line, 100, file)) {
if(strncmp(line, prop, len) != 0)
continue;
p = line + len + 1;
while(isspace(*p)) ++p;
break;
}
return p;
}
int main(int argc, char *argv[]) {
char tgid[40], status[40], *s, *n;
FILE* statusf;
printf("Please Enter PID\n");
if (fgets(tgid, sizeof tgid, stdin)) {
//Remove new line
strtok(tgid, "\n");
snprintf(status, 40, "/proc/%s/status", tgid);
statusf = fopen(status, "r");
if(!statusf){
perror("Error");
return 0;
}
s = getField(statusf, "State:", 6);
n = getField(statusf, "Name:", 5);
printf("State: %s\n", s);
printf("Name: %s\n", n);
}else{
printf("Error on input");
}
fclose(statusf);
return 1;
}
I am still finding the pointers and memory a bit fuzzy. When I run this script without
n = getField(statusf, "Name:", 5);
I get the correct output ( eg. S - Sleeping );
But when I call the function to get the process name I seem to get the same out put for both eg.
State: ntary_ctx Name: ntary_ctx
And that isn't even the right name. I think the issue must be the functions variables are keeping there value. But I thought that when a function return its memory is then pop off the stack.