C++ method of executing Linux Bash command

  • 2020-06-19 11:13:16
  • OfStack

Method 1: the fopen() function


#include<cstdlib>
#include<string>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;

const int N = 300;

void Test(void){
  char line[N];
  FILE *fp;
  string cmd = "ps -ef| grep java | awk '{print $2}'";
  //// The quotes are yours linux instruction 
  //  The system calls 
  const char *sysCommand = cmd.data();
  if ((fp = popen(sysCommand, "r")) == NULL) {
    cout << "error" << endl;
    return;
  }
  while (fgets(line, sizeof(line)-1, fp) != NULL){
    cout << line ;
  }
  pclose(fp);
}

int main(){
  Test();

  return 0;
}

Note:

popen function prototype: FILE * popen(const char * command,const char * type);

popen() calls fork() to generate the child process and then calls ps-ef | grep java | awk '{print $2}' from the child process to execute the instruction for the parameter command. The parameter type can be used "r" for read and "w" for write. popen() creates a pipe to the child's STDOUT or stDOut device and returns a file pointer.

The process can then use the file pointer to read the output device of the child process or to write to its standard input device. In addition, all functions that operate with the file pointer (FILE*) are also available except fclose().

Avoid using popen() when writing programs with SUID/SGID permissions. popen() inherits environment variables, which can cause system security problems.

Or, more simply:

Method 2: the system() function


  #include <cstdlib>
  int main()
  {  
    system("ps -ef| grep java");
    // The parentheses are yours linux instruction 
    return 0;
  }

Note: system() will call fork() to produce a child process, which will call the string "ps-ef | grep java" to execute the command represented by the parameter string string, and then return the original called process after the execution of this command. So using this system() call is one more process than executing ps-ef | grep java.

Do not use system() when writing programs with SUID/SGID permissions. system() inherits environment variables, which may cause system security problems.


Related articles: