Dec
30

How to read system command output from Console In C

Author saurabh    Category Uncategorized     Tags

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.

 

saurabh

hey friends i have completed my B.Tech in CE from Ganpat University & now i am working as Android Middleware & Application Developer in one Private firm. i really enjoy programming…!!

More PostsFacebook

You may like to read this also....

Post comment

*

CommentLuv badge
Follow us on Twitter! Follow us on Twitter!

Search in this website

our sponsors

latest comments

Find us on Facebook

Top Authors

35 posts
saurabh
21 posts
10 posts

Find us on stackoverflow

Polls

Tell us who you are

View Results

Loading ... Loading ...

My Bookmarks

Sponsers Link