使c ++程序以交互方式将input输出传递给windows命令提示符

我想做一个简单的程序,并行地启动一个cmd.exe,并将用户的input作为一个命令,然后传递给cmd.exe,执行后我的程序应该从cmd.exe的输出,并显示它用户。 基本上是一个命令提示符的界面。

我不想使用像system()这样的方法,因为他们每次都启动一个cmd的新实例,而我不能像cd一样运行命令。

我试着用下面的代码来生成一个cmd并显示初始行(copyright ….),但是传递命令只是简单地返回相同的行。

#include <iostream> #include <windows.h> #include <process.h> using namespace std; DWORD WINAPI exec(LPVOID inputP){ char* input=(char*) inputP; HANDLE stdinRd, stdinWr, stdoutRd, stdoutWr; SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES), NULL, true}; STARTUPINFO si; PROCESS_INFORMATION pi; DWORD stuff; char buff[1000]; //Create the main transfer pipe if(!CreatePipe(&stdinRd, &stdinWr, &sa, 0) || !CreatePipe(&stdoutRd,&stdoutWr, &sa, 0)) { cout<<"Pipe creation failed"<<endl; } //Get Process Startup Info GetStartupInfo(&si); si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; si.wShowWindow = SW_SHOW; si.hStdOutput = stdoutWr; si.hStdError = stdoutWr; si.hStdInput = stdinRd; //Create the CMD Shell using the process startup info above if(!CreateProcess("C:\\Windows\\System32\\cmd.exe", NULL, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) { cout<<"Error Spawning Command Prompt."<<endl; } //Main while(1) Loop while(1) { Sleep(100); //Check if cmd.exe has not stoped GetExitCodeProcess(pi.hProcess, &stuff); //Stop the while loop if not active if(stuff != STILL_ACTIVE) break; //Copy Data from buffer to pipe and vise versa PeekNamedPipe(stdoutRd, NULL, 0, NULL, &stuff, NULL); ZeroMemory(buff, sizeof(buff)); //Read Console Output ReadFile(stdoutRd, buff, 1000, &stuff, NULL); //output cout<<buff<<endl; //Read data from stream and pipe it to cmd.exe WriteFile(stdinWr, input, strlen(input), &stuff, NULL); } return 0; } int main() { while(1){ char a[100]; cin>>a; CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)exec, (LPVOID)a, 0, NULL); } } 

发现我的问题,是相当愚蠢的。 只需要传递一个新行字符,以便cmd将数据解释为命令,即,

 cin>>a; strcat(a,"\n"); 

显然通过只调用一次线程并通过全局变量传递参数来创建cmd的单个实例。