Tutorial on how to execute Linux Bash commands in c ++, linuxbash
Method 1: 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 }'"; //// your linux Command is enclosed in quotation marks. // The system calls const char * sysCommand = cmd. data (); if (fp = popen (sysCommand, "r") = NULL) {cout <"error" <endl; return ;} while (fgets (line, size Of (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 a sub-process, and then calls ps-ef | grep java | awk '{print $2}' from the sub-process to execute the command of the parameter command. You can use "r" to indicate reading, and "w" to indicate writing. Popen () creates a standard input for connecting the MPs queue to the sub-process.
Output device or standard input device, and then return a file pointer. Then the process will be available
This file pointer is used to read the output device of a sub-process or to write data to a sub-process.
Enter the device. In addition, all functions that use FILE * operations can also
In addition to fclose.
When writing programs with SUID/SGID permissions, try to avoid using popen (). popen () inherits environment variables, which may cause system security problems.
Or, simpler:
Method 2: system () function
# Include <cstdlib> int main () {system ("ps-ef | grep java"); // your linux Command return 0 in parentheses ;}
Note: system () calls fork () to generate sub-processes. The sub-process calls the string "ps-ef | grep java" to execute the command represented by the string parameter, after the command is executed, the original called process is returned. Therefore, compared to executing ps-ef | grep java directly, one more process id will be used for this system () call.
Do not use system () when writing programs with SUID/SGID permissions. system () inherits environment variables, which may cause system security problems.