How to read output from an External Program? [using popen() function] - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

How to read output from an External Program? [using popen() function]

Share This
In this tutorial, we will discuss a simple way of passing data between two processes. In the following example, the function popen allows invoking a new process. Here, a process uname is created with option -a . The output of the program is available to the invoking program by file pointer my_fp as invoking mode is "r" . Hence, the output can be read by fread function as shown in the following example.


Source code to read the output of a process from an external process
#include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> int main() { FILE *my_fp; char buffer[BUFSIZ + 1]; int no_of_chars; memset(buffer, '\0', sizeof(buffer)); my_fp = popen("uname -a", "r"); if (my_fp != NULL) { no_of_chars = fread(buffer, sizeof(char), BUFSIZ, my_fp); if (no_of_chars > 0) { printf("Output:-\n%s\n", buffer); } pclose(my_fp); exit(EXIT_SUCCESS); } exit(EXIT_FAILURE); }


Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.