我想制作一个简单的程序,并行启动 cmd.exe 并将用户输入作为命令,然后传递给 cmd.exe,执行后我的程序应该从 cmd.exe 获取输出并显示给用户。基本上是命令提示符的界面。
我不想使用像 system() 这样的方法,因为它们每次都会启动一个新的 cmd 实例,而且我无法运行像 cd 这样的命令。
我尝试使用以下代码生成一个 cmd 并显示初始行(版权....),但传递命令只会再次返回同一行。
#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 的单个实例。
关于c++ - 使c++程序以交互方式将输入输出传递给windows命令提示符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28222285/