How to read system command output from Console In C
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.
So this way you can use to do this.
Here we use popen in read mode
The popen() function shall execute the command specified by the string command. It shall create a pipe between the calling program and the executed command, and shall return a pointer to a stream that can be used to either read from or write to the pipe.
Code : -
#include #include int main( int argc, char *argv[] ) { FILE *fp; int status; char path[1035]; /* Open the command for reading. */ fp = popen("ping 4.2.2.2 2>&1", "r"); if (fp == NULL) { printf("Failed to run command\n" ); exit; } /* Read the output a line at a time - output it. */ while (fgets(path, sizeof(path)-1, fp) != NULL) { printf("%s", path); } /* close */ pclose(fp); return 0; } |
And if you want to fetch error messages from console so You can use 2>&1
in fp = popen("ping 4.2.2.2 2>&1", "r");
this line instead of fp = popen("ping 4.2.2.2", "r");
Because
0=stdin
; 1=stdout
; 2=stderr
If you do 2>1
that will redirect all the stderr
to a file named 1
. To actually redirect stderr
tostdout
you need to use 2>&1
. &1
means passing the handle to the stdout
.
You may like to read this also....
Post comment
Search in this website
our sponsors
latest comments
- Shah Dhaval on How to detect memory leakage in C program?
- ruunyytikkil on how can I write applications in C or C++ for Android?
- anonym on How to convert SQL to Excel in Php?
- Academic Projects and Tech interview on C programming interview questions and answers for freshers
- Motasim billah on List of all standard version of c language
Find us on Facebook
Top Authors
Find us on stackoverflow
Polls
My Bookmarks
- Audio/video Recorder & player application based on MATLAB
- check dependency of your binary
- defination of all standard c programming language function
- Great Question-Answer on c programming
- know what your c code means
- Limition of c programming language
- List of all version of c programming language
- Online c compiler
- php freelancing work
- some more stuff on C programming language
- Volatile Keyword in Embedded System
- Write Android application in c language