1 #include <Windows.h>
2 #include <process.h>
3
4 #include "Process.h"
5
readOutput(void * p)6 void* readOutput( void* p )
7 {
8 HANDLE hReadPipe = p;
9 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
10 char chBuf[128];
11 DWORD dwRead, dwWritten;
12
13 while(true)
14 {
15 if( !ReadFile( hReadPipe, chBuf, 128, &dwRead,
16 NULL) || dwRead == 0) break;
17 if (! WriteFile(hStdOut, chBuf, dwRead, &dwWritten, NULL))
18 break;
19 }
20 return 0;
21 }
22
23 namespace ATRUN
24 {
create()25 void Process::create()
26 {
27 SECURITY_ATTRIBUTES sa;
28 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
29 sa.bInheritHandle = TRUE;
30 sa.lpSecurityDescriptor = NULL;
31
32
33 STARTUPINFO info;
34 GetStartupInfo(&info);
35
36 char curdir[100];
37 GetCurrentDirectory(sizeof(curdir), curdir);
38
39 SetCurrentDirectory( const_cast<char*>(m_workingDir.c_str()) );
40
41 HANDLE hReadPipe, hWritePipe;
42 if(m_sendToFile)
43 {
44 openOutFile();
45 info.dwFlags = STARTF_USESTDHANDLES;
46 CreatePipe(&hReadPipe, &hWritePipe, &sa, 0);
47 info.hStdOutput = m_outFileHandle;
48 info.hStdError = m_outFileHandle;
49 }
50
51 else if(m_sendToStd)
52 {
53 info.dwFlags = STARTF_USESTDHANDLES;
54 CreatePipe(&hReadPipe, &hWritePipe, &sa, 0);
55 info.hStdOutput = hWritePipe;
56 info.hStdError = hWritePipe;
57 }
58
59 m_created = CreateProcess(
60 NULL,
61 const_cast<char*>(m_commandLine.c_str()),
62 NULL,
63 NULL,
64 TRUE,
65 getFlags(),
66 NULL,
67 NULL,
68 &info,
69 &m_procinfo ) != 0;
70
71 if(m_created && (m_sendToFile || m_sendToStd))
72 _beginthread((void(__cdecl*)(void*))readOutput, 0, hReadPipe);
73
74 SetCurrentDirectory( curdir );
75 }
76
terminate()77 void Process::terminate()
78 {
79 if(m_created)
80 {
81 TerminateProcess(m_procinfo.hProcess, 0);
82 reset();
83 }
84 }
85
waitFor()86 void Process::waitFor()
87 {
88 WaitForSingleObject(m_procinfo.hProcess, INFINITE);
89 reset();
90 }
91
reset()92 void Process::reset()
93 {
94 GetExitCodeProcess(m_procinfo.hProcess, &m_exitCode);
95 CloseHandle(m_procinfo.hProcess);
96 m_created = false;
97 m_procinfo.dwThreadId = -1;
98
99 if( m_isOutFileOpen )
100 {
101 closeOutFile();
102 }
103 }
104
openOutFile()105 void Process::openOutFile()
106 {
107 SECURITY_ATTRIBUTES sa;
108
109 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
110 sa.bInheritHandle = TRUE;
111 sa.lpSecurityDescriptor = NULL;
112
113 m_outFileHandle = CreateFile(
114 m_outFile.c_str(),
115 GENERIC_WRITE,
116 0, //open exclusively
117 &sa,
118 CREATE_ALWAYS,
119 FILE_ATTRIBUTE_NORMAL,
120 NULL );
121
122 m_isOutFileOpen = true;
123 }
124
closeOutFile()125 void Process::closeOutFile()
126 {
127 CloseHandle(m_outFileHandle);
128 m_isOutFileOpen = false;
129 }
130
getFlags()131 DWORD Process::getFlags()
132 {
133 if(m_showWindow)
134 return CREATE_NEW_CONSOLE;
135
136 return CREATE_NO_WINDOW;
137 }
138 }