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

标签 c++ windows multithreading pipe ipc

我想制作一个简单的程序,并行启动 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/

相关文章:

c++ - svn重命名问题

C++ "extra"头文件

c++ - 独立的 Windows 应用程序在焦点改变时挂起

windows - Delphi 应用程序与偶尔崩溃的程序通信 - 供应商指责我的 Delphi 应用程序

c++ - char[9][9] 的初始值设定项太多

c# - 为什么无限在Windows 10控制台中打印为 "8"?

java - 为什么这段代码的结果是不确定的?

java - 我能以更好的方式加入线程吗?

Java:带有 Callables 的 ExecutorService:在循环中重用同一个池?需要关机吗?

c++ - 从另一个进程中查找变量的地址