I wrote a routine that allows me to make windows system calls from an application, trap the response into a buffer so the content of the buffer can be used in my application. Every command I've tried, until today, has worked without a flaw, including those with very large response buffers. The basic steps are as follows:
1) start a child cmd prompt process from application 2) write a command to it's stdin, eg: 3) "cmd.exe /c dir" (returns listing of applications host directory) 4) capture response from stdout
for most commands, making the call and getting the response is normally as simple as:
int main(void)
{
char *buf = {0};
buf = calloc(100, 1);
if(!buf)return 0;
cmd_rsp("dir /s", &buf, 100);//cmd_rsp is fully defined in the links I provided in post.
//Note: all commands are prepended with
//'cmd.exe /c ' inside the cmd_rsp function.
printf("%s", buf);
free(buf);
return 0;
}
But when I send the command powershell start-sleep -m 2000
, nothing is ever sent to stdout
, causing application to hang.
Execution flow stops at the ReadFile
function, trying to catch at least one byte of data out through the stdout
pipe. ( refer to code here )
I have read (and tried the suggestions in) this link about this topic, but still have not seen results using the &
to concatenate the calls. i.e., the &
does work with combination calls such as:
cmd.exe /c cd c:\\devphys\\msvc\\ && dir
Just not when powershell
is called.
I am hoping someone familiar with this scenario can suggest a different calling convention when using such things as powershell
in the command line, Or, suggest a way to break out of ReadFile
(called from within the function ReadFromPipe
) when it is clear nothing is coming to stdout
.
EDIT: in the code for cmd_rsp(...) , some may have noticed that inside the function ReadFromPipe
, I made an attempt at a timeout using:
//Set timeouts for stream
ct.ReadIntervalTimeout = 0;
ct.ReadTotalTimeoutMultiplier = 0;
ct.ReadTotalTimeoutConstant = 10;
ct.WriteTotalTimeoutConstant = 0;
ct.WriteTotalTimeoutMultiplier = 0;
SetCommTimeouts(g_hChildStd_OUT_Rd, &ct);
However, as detailed here and here (see comment under post). this method, as a timeout, is not compatible with an implementation using ReadFile
and pipes.