C++ में सिस्टम कमांड एक्जीक्यूट करने और उसका आउटपुट प्राप्त करने के लिए popen() (POSIX) का उपयोग करें। system() केवल एग्जिट कोड लौटाता है, आउटपुट नहीं।
विधि 1: popen() - आउटपुट पढ़ने के लिए
#include <iostream>
#include <cstdio>
#include <memory>
#include <string>
using namespace std;
string execCommand(const string &cmd) {
const int bufferSize = 128;
char buffer[bufferSize];
string result;
// "r" मोड: कमांड के stdout को पढ़ें
unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd.c_str(), "r"), pclose);
if (!pipe) {
throw runtime_error("popen() failed!");
}
while (fgets(buffer, bufferSize, pipe.get()) != nullptr) {
result += buffer;
}
return result;
}
int main() {
try {
// सिंपल कमांड
cout << "=== echo command ===\n";
cout << execCommand("echo 'Hello World'");
// मैथ एक्सप्रेशन
cout << "\n=== bc calculator ===\n";
cout << execCommand("echo '22 / 7' | bc -l");
// सिस्टम इन्फो
cout << "\n=== System info ===\n";
cout << execCommand("uname -a");
// डिस्क उपयोग
cout << "\n=== Disk usage ===\n";
cout << execCommand("df -h /");
} catch (const exception &e) {
cerr << "Error: " << e.what() << endl;
}
return 0;
}
आउटपुट
=== echo command === Hello World === bc calculator === 3.14285714285714285714 === System info === Linux hostname 5.15.0-91-generic #101-Ubuntu SMP x86_64 GNU/Linux === Disk usage === Filesystem Size Used Avail Use% Mounted on /dev/sda1 500G 120G 380G 24% /
विधि 2: stderr भी कैप्चर करना
string execCommandWithError(const string &cmd) {
// stderr को stdout में रीडायरेक्ट करें
string fullCmd = cmd + " 2>&1";
return execCommand(fullCmd);
}
विधि 3: C++23 std::process (भविष्य)
// C++23 प्रस्तावित (अभी तक मानक नहीं)
#include <process>
int main() {
std::process p("echo", "Hello");
auto result = p.wait();
cout << result.stdout();
}
विधि 4: Boost.Process (वर्तमान में सर्वश्रेष्ठ क्रॉस-प्लेटफॉर्म)
#include <boost/process.hpp>
#include <iostream>
#include <string>
namespace bp = boost::process;
int main() {
bp::ipstream out;
bp::child c("echo Hello World", bp::std_out > out);
string line;
while (c.running() && std::getline(out, line)) {
cout << line << '\n';
}
c.wait();
// आर्गुमेंट्स के साथ
bp::child c2("bc", "-l", bp::std_in < "22/7\n", bp::std_out > out);
c2.wait();
return 0;
}
सुरक्षा चेतावनी
- कमांड इंजेक्शन: कभी भी अनट्रस्टेड इनपुट को सीधे कमांड में न डालें
- शेल इंजेक्शन:
popen("cmd " + userInput, ...)खतरनाक है - समाधान: आर्गुमेंट्स को अलग-अलग पास करें (Boost.Process, posix_spawn) या इनपुट सैनेटाइज करें
// ❌ असुरक्षित
system("echo " + userInput);
// ✅ सुरक्षित: Boost.Process आर्गुमेंट वेक्टर
bp::child c("echo", userInput, bp::std_out > out);
// ✅ सुरक्षित: एस्केप करें (केवल शेल के लिए)
string escaped = shellEscape(userInput);
system("echo " + escaped);