Make c++ program to pass input output to windows command prommpt interactively

痞子三分冷 提交于 2019-12-24 16:54:30

问题


I want to make a simple program that starts a cmd.exe parallely and takes input from the user as a command, which is then passed to the cmd.exe, after execution my program should take the output from cmd.exe and display it to the user. Basically an interface to a command prompt.

I don't want to use methods like system() as they start a new instance of cmd every time and I can't run commands like cd.

I tried it with the following code with which I am able to spawn a cmd and show initial line (copyright....), but passing commands simply returns the same line again.

#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);
}
}

回答1:


Found my problem, was quite silly. Just need to pass a new line character so that cmd interprets the data as a command, i.e.,

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

and obviously make a single instance of cmd by calling the thread only once and passing parameters through global variables.



来源:https://stackoverflow.com/questions/28222285/make-c-program-to-pass-input-output-to-windows-command-prommpt-interactively

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!