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
  • 349,597
  • 67
  • 533
  • 578
user3483203
  • 50,081
  • 9
  • 65
  • 94

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,470
  • 15
  • 21