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