1월, 2021의 게시물 표시

C++ - Two-way communication with child processes(using stdout/stdin)

 While programming, we often run other processes and receive the result value and proceed to the next task.  I often use the subprocess module in Python to do this.  In C/C++ programming, popen and system functions are often used. To receive the stdout output value of the child process, use the popen function, and when only the return value of the end of the child process is needed, use the system function. #include <iostream> #include <cstring> using namespace std; string exec_command ( const char * cmd) { string retstr( "" ); char buffer[ 1024 ]; FILE * pipe = popen(cmd, "r" ); if (pipe) { try { while ( ! feof(pipe)) { if (fgets(buffer, sizeof (buffer), pipe) != NULL) retstr += buffer; } } catch (...) { } pclose(pipe); } return retstr; } int main () ...