C: Run a System Command and Get Output? [duplicate]
Asked Answered
L

2

172

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?

Lathe answered 14/3, 2009 at 16:54 Comment(0)
C
318

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;
}
Consign answered 14/3, 2009 at 17:1 Comment(8)
Redirecting stderr to stdout may be a good idea, so you catch errors.Pringle
how would i redirect stderr to stdout?Lathe
you should use fgets(path, sizeof(path), fp) not sizeof(path)-1. read the manualRelieve
@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");Livesay
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 exitCoronach
Thanks! Very helpful. FYI, it appears that int status is not being used. No big deal. EDIT: I removed it.Dockyard
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?Silkaline
The buffer will be empty/unset.Consign
D
5

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

Dressage answered 14/3, 2009 at 16:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.