Monday, 30 January 2017

Execute shell command using popen() in C/C++


The popen() syscall executes a command and pipes the executes command to the calling program.
This syscall return a pointer to the stream which can be used by calling program to read and write to the pipe.

Below are the C/C++ snippets to run a simple command, read the stream from pipe (execute ls command)  and then write to console (display to console)

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

int main(void)  {
 FILE *fp;
 char buff[1024];

 //Return NULL if popen fail 
 if(!(fp = popen("ls -sail", "r"))){
     printf("Fail to open popen\n");
     exit(1);
 }

 //Read the stream and print on screen
 while(fgets(buff, sizeof(buff), fp)!=NULL){
     printf("%s", buff);
 }

 pclose(fp);
 return 0;
}


No comments:

Post a Comment