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?
Asked
Active
Viewed 3.2e+01k times
2 Answers
315
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;
}

Matt K
- 6,620
- 3
- 38
- 60
-
1Redirecting stderr to stdout may be a good idea, so you catch errors. – Mar 14 '09 at 17:12
-
how would i redirect stderr to stdout? – jimi hendrix Mar 14 '09 at 21:06
-
13you should use `fgets(path, sizeof(path), fp)` not `sizeof(path)-1`. read the manual – user102008 Dec 22 '10 at 00:25
-
4@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"); – rakslice Apr 05 '11 at 22:25
-
1There 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 – Sachin Jul 13 '12 at 18:42
-
Thanks! Very helpful. FYI, it appears that `int status` is not being used. No big deal. EDIT: I removed it. – arr_sea May 08 '13 at 00:51
-
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? – dexterous Feb 18 '18 at 02:24
-
The buffer will be empty/unset. – Feb 23 '18 at 04:02
5
You need some sort of Inter Process Communication. Use a pipe or a shared buffer.

dirkgently
- 108,024
- 16
- 131
- 187