Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Thực thi lệnh shell và lấy kết quả trong C++ (POSIX)


Sử dụng popen() / pclose() (POSIX) để chạy lệnh shell và đọc đầu ra(stdout) của lệnh đó trong chương trình C++.

Ví dụ mã nguồn

#include <iostream>
#include <cstdio>
#include <memory>
using namespace std;

string execCommand(const char* cmd) {
    array<char, 128> buffer;
    string result;
    unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd, "r"), pclose);
    if (!pipe) throw runtime_error("popen failed");
    while (fgets(buffer.data(), buffer.size(), pipe.get()))
        result += buffer.data();
    return result;
}

int main() {
    cout << "Chay 'echo Hello':\n" << execCommand("echo 'Hello World'") << "\n";
    cout << "Tinh 22/7 voi bc:\n" << execCommand("echo '22/7' | bc -l") << "\n";
    cout << "Nguoi dung hien tai:\n" << execCommand("whoami") << "\n";
    return 0;
}

Đầu ra mẫu

Chay 'echo Hello':
Hello World

Tinh 22/7 voi bc:
3.14285714285714285714

Nguoi dung hien tai:
ubuntu

Lưu ý

  • popen chỉ đọc stdout. Cần 2>&1 để bắt stderr.
  • Chỉ hoạt động trên hệ thống POSIX (Linux, macOS).
  • C++23 dự kiến có std::process đa nền tảng.