menu

Questions & Answers

C: Run a System Command and Get Output?

I want to run a command in linux and get the text returned of what it outputs, but I do not want this text printed to screen. Is there a more elegant way than making a temporary file?

Answers(2) :

You want the "popen" function. Here's an example of running the command "ls /etc" and outputing to the console.

#include <stdio.h>
#include <stdlib.h>


int main( int argc, char *argv[] )
{

  FILE *fp;
  char path[1035];

  /* Open the command for reading. */
  fp = popen("/bin/ls /etc/", "r");
  if (fp == NULL) {
    printf("Failed to run command\n" );
    exit(1);
  }

  /* Read the output a line at a time - output it. */
  while (fgets(path, sizeof(path), fp) != NULL) {
    printf("%s", path);
  }

  /* close */
  pclose(fp);

  return 0;
}
Comments:
2023-01-21 23:52:06
Redirecting stderr to stdout may be a good idea, so you catch errors.
2023-01-21 23:52:06
how would i redirect stderr to stdout?
2023-01-21 23:52:06
you should use fgets(path, sizeof(path), fp) not sizeof(path)-1. read the manual
2023-01-21 23:52:06
@jimi: You can redirect stderr to stdout in the shell command you're running through popen, e.g. fp = popen("/bin/ls /etc/ 2>&1", "r");
2023-01-21 23:52:06
There seems to be a 2 way communication using popen, if I issue a command that prompts the user for confirmation then I get the prompt. What I can I do if I just want to read the output and if there is prompt then I just exit
2023-01-21 23:52:06
Thanks! Very helpful. FYI, it appears that int status is not being used. No big deal. EDIT: I removed it.
2023-01-21 23:52:06
Let's assume there are no files inside /etc/, then what will be stored in path variable? I am asking this because I am planning to run pidOf node instead of ls -l . Let's assume node is not running then pidOf node will return nothing. In such a case, what will return in path variable here?
2023-01-21 23:52:06
The buffer will be empty/unset.

You need some sort of Inter Process Communication. Use a pipe or a shared buffer.