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

Thực thi lệnh và lấy đầu ra trong C++ dùng POSIX (popen)


Dùng hàm popen và pclose để tạo pipe tới/từ tiến trình. popen() mở tiến trình bằng cách tạo pipe, fork, và gọi shell. Dùng buffer đọc stdout và nối vào chuỗi kết quả, trả về khi tiến trình kết thúc.

Ví dụ

#include <iostream>
#include <stdexcept>
#include <stdio.h>
#include <string>
using namespace std;

string exec(string command) {
    char buffer[128];
    string result = "";
    FILE* pipe = popen(command.c_str(), "r");
    if (!pipe) return "popen failed!";
    while (!feof(pipe)) {
        if (fgets(buffer, 128, pipe) != NULL)
            result += buffer;
    }
    pclose(pipe);
    return result;
}

int main() {
    string ls = exec("ls");
    cout << ls;
}

Đầu ra (ví dụ)

a.out hello.cpp hello.py hello.o hydeout my_file.txt watch.py