คุณสามารถใช้ฟังก์ชัน popen และ pclose เพื่อไพพ์เข้าและออกจากกระบวนการ ฟังก์ชัน popen() จะเปิดกระบวนการโดยการสร้างไพพ์ การฟอร์ก และเรียกใช้เชลล์ เราสามารถใช้บัฟเฟอร์เพื่ออ่านเนื้อหาของ stdout และต่อท้ายสตริงผลลัพธ์และส่งคืนสตริงนี้เมื่อออกจากกระบวนการ
ตัวอย่าง
#include <iostream>
#include <stdexcept>
#include <stdio.h>
#include <string>
using namespace std;
string exec(string command) {
char buffer[128];
string result = "";
// Open pipe to file
FILE* pipe = popen(command.c_str(), "r");
if (!pipe) {
return "popen failed!";
}
// read till end of process:
while (!feof(pipe)) {
// use buffer to read and add to result
if (fgets(buffer, 128, pipe) != NULL)
result += buffer;
}
pclose(pipe);
return result;
}
int main() {
string ls = exec("ls");
cout << ls;
} ผลลัพธ์
สิ่งนี้จะให้ผลลัพธ์ -
a.out hello.cpp hello.py hello.o hydeout my_file.txt watch.py