SWAT Blog

popen() – execute shell command from C/C++

March 23rd, 2011 by Atul Sharma

The popen() function executes a command and pipes the executes command to the calling program, returning a pointer to the stream which can be used by calling program to read/write to the pipe.
Below are the C/C++ snippets to run a simple command, read the stream from pipe and then write to console.

C Implementation

#include <stdio.h>

int main(void) {
	FILE *in;
	extern FILE *popen();
	char buff[512];

	if(!(in = popen("ls -sail", "r"))){
		exit(1);
	}

	while(fgets(buff, sizeof(buff), in)!=NULL){
		printf("%s", buff);
	}
	pclose(in);

}

C++ Implementation

#include <iostream>
#include <stdio.h>

using namespace std;

int main() {
	FILE *in;
	char buff[512];

	if(!(in = popen("ls -sail", "r"))){
		return 1;
	}

	while(fgets(buff, sizeof(buff), in)!=NULL){
		cout << buff;
	}
	pclose(in);

	return 0;
}

popen() is included in SUS version 2. More details can be found at http://pubs.opengroup.org/onlinepubs/007908799/xsh/popen.html

Tags: , ,

Leave a Reply

  • © 2004-2012 Special Work & Technology Limited