0

I am trying to print running processes on a linux system, but I am getting a segmentation fault when trying to do so. Here is my code:

FILE *ps;
char line[256];
char * command = "ps";  
ps = fopen(command, "r");
if(ps == NULL){
    perror("Error");
}
while(fgets(line, sizeof(line), ps)){
    printf("%s", line);
}
fclose(ps);

The odd thing is that when I use the same code but replace "ps" with "/proc/meminfo" or other files, it will correctly output. Thanks in advance for the help.

John Kugelman
  • 330,190
  • 66
  • 504
  • 555
user3483203
  • 48,205
  • 9
  • 52
  • 84

1 Answers1

3

Try to use popen and pclose for running command rather than fopen and fclose

char line[256];
FILE *ps = popen("ps", "r");
if(ps == NULL){
    perror("Error");
}

while(fgets(line, sizeof(line), ps)){
    printf("%s", line);
}

pclose(ps);
Like
  • 1,392
  • 13
  • 21