Reputation: 13
C BEGINNER WARNING!!!
I am writing an application in c, that is supposed to run a user defined command in the context of "cmd.exe" and write the output to a variable. For example if the command variable was "dir C:\" the c programm should use CreateProcess() to start cmd.exe, input "dir C:\" and return the output to a variable. As of right now the code i have so far is:
char cmmndoutput[256];
char userdefcmmnd[256] = "dir C:\\";
STARTUPINFO sui;
PROCESS_INFORMATION pi;
memset(&sui, 0,sizeof(sui));
sui.cb = sizeof(sui);
sui.dwFlags = (STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW);
sui.hStdInput = userdefcmmnd[];
sui.hStdOutput = cmmndoutput[];
TCHAR cmdvar[256] = "cmd.exe";
CreateProcess(cmdvar, userdefcmmnd, NULL, NULL, TRUE, 0, NULL, NULL, &sui, &pi);
// wait 5 seconds or program exit somehow
printf("%s",cmmndoutput[]); // or do something with the output
Note: The programm should wait a specific time for the command and should not wait until cmd.exe exits like system() would.
Thanks for your patience, i am new to c and have definetly got alot of things wrong in this code. Any help is appreciated!
Upvotes: 0
Views: 617
Reputation: 43278
sui.hStdInput = userdefcmmnd[];
sui.hStdOutput = cmmndoutput[];
hStdInput
and hStdOutput
aren't arrays. They take handles, typically the result of CreatePipe()
but file handles could be used as well.
The general form is to use two or three calls CreatePipe()
with a SECURITY_ATTRIBUTES
with bInheritHandles = TRUE
and SetHandleInformation()
on the side not being redirected to prevent it from being forwarded. The handles from CreatePipe()
can be converted to FILE *
objets by _open_osfhandle()
followed by _fdopen()
.
You won't be able to use FILE *
objects on your read side because of your five second timeout requirement. Pipe handles and background streams are tricky business. The only way I've gotten timeouts to work right is to use a background thread to read the pipe input with ReadFile()
and use CancelIoEx()
to give up when timeout is reached.
And you claim to be a beginning C programmer. I am sorry. The number of advanced topics this code invokes the advanced topics of multi-process, multi-threading, and the slight buggyness and general complexity of the bottom-level IO of Windows. If you can get out of doing this you will be happier.
Upvotes: 1