On Saturday, 15 March 2014 at 22:48:52 UTC, Adam D. Ruppe wrote:
On Saturday, 15 March 2014 at 19:11:38 UTC, Bauss wrote:
Note I am not typing the arguments, but rather starting the process.

Skip to the bottom of this message if you are doing it in D and don't care how it is done in the lower level api.


The CreateProcess API call takes a STARTUPINFO argument which has handles you can use to redirect the output. 2>somefile.txt in cmd.exe does something like this:

HANDLE hFile = CreateFile("somefile.txt", GENERIC_WRITE, 0, null, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, null); if(hFile == INVALID_HANDLE_VALUE) throw new Exception("couldn't open file");
scope(exit) CloseHandle(hFile);

STARTUPINFO si;
si.cb = si.sizeof;
si.dwFlags = STARTF_USESTDHANDLES;
si.hStdError = hFile; // redirect to our file
si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);



// Now, we'll create the process with the file set up and wait for it to finish


PROCESS_INFORMATION pi;

if(CreateProcessA("dmd.exe", "dmd.exe yourfile.d", null, null, true, 0, null, null, &si, &pi) == 0)
   throw new Exception("createProcess failed");

WaitForSingleObject(pi.hProcess, INFINITE);

CloseHandle(pi.hProcess);

// At this point, we could check out somefile.txt to see what is there





Of course, if we wanted to see the content in our program, instead of going through a regular file, we could use CreatePipe() to make a pair, passing the write handle to it as the hStdOutput, then reading from the read side to collect all the program's output in memory.

There's similar Posix functions if you want to do this kind of thing on linux, etc., too.



If you're writing this program in D, the standard library contains a nice little function to make this a lot shorter:

http://dlang.org/phobos/std_process.html#.execute

the example there calls dmd too! So if you wanna try it from D, copy/paste that example and it should get you started.

Actually I was doing it through C#. I have tried getting the output of the window but it doesn't seem to redirect it.

Reply via email to