how to read bash shell command output in c program. In this tutorial we will learn about Linux popen system call. popen system call can be used to read bash shell command output. The popen()  and pclose() system call is easier to use.

From Linux manual:

 The popen() function opens a process by creating a pipe, forking, and invoking the shell.  Since
 a pipe is by definition unidirectional,the type argument may specify only reading or writing, not
 both; the resulting stream is correspondingly read-only or write-only.

Let us write a simplest shell command.

echo "Hello WikiStack"

 it will print Hello WikiStack on terminal output.

Now we will write a simple c program using popen() system call which will execute our shell command. popen() function returns a stream. we will read shell command output by using this stream.

how to read bash shell command output in c program

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>

// make bash command
char *command = "echo Hello WikiStack";

int main() {

	FILE *p;
	p = popen(command, "r");

	if (!p) {
		fprintf(stderr, "Error opening pipe.\n");
		return 1;
	}

	char string[100];
	while(fgets(string, 100, p)) {
	    printf("%s\n", string);
	}

	if (pclose(p) == -1) {
		fprintf(stderr, " Error!\n");
		return 1;
	}

	return 0;
}

Note: Do comment if there is more improved way.

Ref:

http://stackoverflow.com/questions/9434207/reading-from-file-using-fgets



Related Contents to follow