]> git.saurik.com Git - wxWidgets.git/blame - src/msw/utilsexc.cpp
* build and distrib tweaks.
[wxWidgets.git] / src / msw / utilsexc.cpp
CommitLineData
32592631 1/////////////////////////////////////////////////////////////////////////////
b568d04f 2// Name: msw/utilsexec.cpp
79066131 3// Purpose: wxExecute implementation for MSW
32592631
GL
4// Author: Julian Smart
5// Modified by:
6// Created: 04/01/98
7// RCS-ID: $Id$
77ffb593 8// Copyright: (c) 1998-2002 wxWidgets dev team
65571936 9// Licence: wxWindows licence
32592631
GL
10/////////////////////////////////////////////////////////////////////////////
11
b568d04f
VZ
12// ============================================================================
13// declarations
14// ============================================================================
15
16// ----------------------------------------------------------------------------
17// headers
18// ----------------------------------------------------------------------------
19
14f355c2 20#if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
b568d04f 21 #pragma implementation
32592631
GL
22#endif
23
24// For compilers that support precompilation, includes "wx.h".
25#include "wx/wxprec.h"
26
27#ifdef __BORLANDC__
b568d04f 28 #pragma hdrstop
32592631
GL
29#endif
30
31#ifndef WX_PRECOMP
b568d04f
VZ
32 #include "wx/utils.h"
33 #include "wx/app.h"
34 #include "wx/intl.h"
068a7cfe 35 #include "wx/log.h"
2ae8a353 36#endif
32592631 37
eccd1992
VZ
38#include "wx/stream.h"
39#include "wx/process.h"
dbeac4bd 40
e2478fde
VZ
41#include "wx/apptrait.h"
42
eccd1992
VZ
43#include "wx/module.h"
44
32592631 45#include "wx/msw/private.h"
dbeac4bd 46
32592631
GL
47#include <ctype.h>
48
4676948b 49#if !defined(__GNUWIN32__) && !defined(__SALFORDC__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
b568d04f 50 #include <direct.h>
17dff81c 51#ifndef __MWERKS__
b568d04f 52 #include <dos.h>
32592631 53#endif
17dff81c 54#endif
32592631 55
b39dbf34 56#if defined(__GNUWIN32__)
b568d04f
VZ
57 #include <sys/unistd.h>
58 #include <sys/stat.h>
57c208c5 59#endif
32592631 60
eccd1992
VZ
61#if !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
62 #ifndef __UNIX__
63 #include <io.h>
64 #endif
32592631 65
eccd1992
VZ
66 #ifndef __GNUWIN32__
67 #include <shellapi.h>
68 #endif
32592631
GL
69#endif
70
71#include <stdio.h>
72#include <stdlib.h>
73#include <string.h>
74#ifndef __WATCOMC__
3f4a0c5b
VZ
75 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
76 #include <errno.h>
77 #endif
32592631
GL
78#endif
79#include <stdarg.h>
80
731dd422
VZ
81#if wxUSE_IPC
82 #include "wx/dde.h" // for WX_DDE hack in wxExecute
83#endif // wxUSE_IPC
5bd3a2da 84
eccd1992 85// implemented in utils.cpp
487f2d58 86extern "C" WXDLLIMPEXP_BASE HWND
eccd1992
VZ
87wxCreateHiddenWindow(LPCTSTR *pclassname, LPCTSTR classname, WNDPROC wndproc);
88
b568d04f
VZ
89// ----------------------------------------------------------------------------
90// constants
91// ----------------------------------------------------------------------------
92
cb6827a8
VZ
93// this message is sent when the process we're waiting for terminates
94#define wxWM_PROC_TERMINATED (WM_USER + 10000)
32592631 95
b568d04f
VZ
96// ----------------------------------------------------------------------------
97// this module globals
98// ----------------------------------------------------------------------------
99
100// we need to create a hidden window to receive the process termination
101// notifications and for this we need a (Win) class name for it which we will
102// register the first time it's needed
eccd1992 103static const wxChar *wxMSWEXEC_WNDCLASSNAME = wxT("_wxExecute_Internal_Class");
b568d04f
VZ
104static const wxChar *gs_classForHiddenWindow = NULL;
105
106// ----------------------------------------------------------------------------
107// private types
108// ----------------------------------------------------------------------------
109
cb6827a8
VZ
110// structure describing the process we're being waiting for
111struct wxExecuteData
112{
113public:
114 ~wxExecuteData()
115 {
116 if ( !::CloseHandle(hProcess) )
117 {
f6bcfd97 118 wxLogLastError(wxT("CloseHandle(hProcess)"));
cb6827a8
VZ
119 }
120 }
121
122 HWND hWnd; // window to send wxWM_PROC_TERMINATED to
123 HANDLE hProcess; // handle of the process
124 DWORD dwProcessId; // pid of the process
125 wxProcess *handler;
126 DWORD dwExitCode; // the exit code of the process
27d2dbbc 127 bool state; // set to false when the process finishes
32592631
GL
128};
129
eccd1992
VZ
130class wxExecuteModule : public wxModule
131{
132public:
133 virtual bool OnInit() { return true; }
134 virtual void OnExit()
135 {
136 if ( *gs_classForHiddenWindow )
137 {
138 if ( !::UnregisterClass(wxMSWEXEC_WNDCLASSNAME, wxGetInstance()) )
139 {
140 wxLogLastError(_T("UnregisterClass(wxExecClass)"));
141 }
142
143 gs_classForHiddenWindow = NULL;
144 }
145 }
146
147private:
148 DECLARE_DYNAMIC_CLASS(wxExecuteModule)
149};
150
151#if wxUSE_STREAMS && !defined(__WXWINCE__)
8b33ae2d 152
8b33ae2d
GL
153// ----------------------------------------------------------------------------
154// wxPipeStreams
155// ----------------------------------------------------------------------------
156
f6bcfd97
BP
157class wxPipeInputStream: public wxInputStream
158{
8b33ae2d
GL
159public:
160 wxPipeInputStream(HANDLE hInput);
79066131 161 virtual ~wxPipeInputStream();
8b33ae2d 162
27d2dbbc 163 // returns true if the pipe is still opened
79066131
VZ
164 bool IsOpened() const { return m_hInput != INVALID_HANDLE_VALUE; }
165
27d2dbbc 166 // returns true if there is any data to be read from the pipe
2b5f62a0 167 virtual bool CanRead() const;
f6bcfd97 168
8b33ae2d
GL
169protected:
170 size_t OnSysRead(void *buffer, size_t len);
171
172protected:
173 HANDLE m_hInput;
22f3361e
VZ
174
175 DECLARE_NO_COPY_CLASS(wxPipeInputStream)
8b33ae2d
GL
176};
177
f6bcfd97
BP
178class wxPipeOutputStream: public wxOutputStream
179{
8b33ae2d
GL
180public:
181 wxPipeOutputStream(HANDLE hOutput);
79066131 182 virtual ~wxPipeOutputStream();
8b33ae2d
GL
183
184protected:
185 size_t OnSysWrite(const void *buffer, size_t len);
186
187protected:
188 HANDLE m_hOutput;
22f3361e
VZ
189
190 DECLARE_NO_COPY_CLASS(wxPipeOutputStream)
8b33ae2d
GL
191};
192
79066131
VZ
193// define this to let wxexec.cpp know that we know what we're doing
194#define _WX_USED_BY_WXEXECUTE_
195#include "../common/execcmn.cpp"
196
197// ----------------------------------------------------------------------------
198// wxPipe represents a Win32 anonymous pipe
199// ----------------------------------------------------------------------------
200
201class wxPipe
202{
203public:
204 // the symbolic names for the pipe ends
205 enum Direction
206 {
207 Read,
208 Write
209 };
210
211 // default ctor doesn't do anything
212 wxPipe() { m_handles[Read] = m_handles[Write] = INVALID_HANDLE_VALUE; }
213
27d2dbbc 214 // create the pipe, return true if ok, false on error
79066131
VZ
215 bool Create()
216 {
217 // default secutiry attributes
218 SECURITY_ATTRIBUTES security;
219
220 security.nLength = sizeof(security);
221 security.lpSecurityDescriptor = NULL;
222 security.bInheritHandle = TRUE; // to pass it to the child
223
224 if ( !::CreatePipe(&m_handles[0], &m_handles[1], &security, 0) )
225 {
226 wxLogSysError(_("Failed to create an anonymous pipe"));
227
27d2dbbc 228 return false;
79066131
VZ
229 }
230
27d2dbbc 231 return true;
79066131
VZ
232 }
233
27d2dbbc 234 // return true if we were created successfully
79066131
VZ
235 bool IsOk() const { return m_handles[Read] != INVALID_HANDLE_VALUE; }
236
237 // return the descriptor for one of the pipe ends
82baa5e4 238 HANDLE operator[](Direction which) const { return m_handles[which]; }
79066131
VZ
239
240 // detach a descriptor, meaning that the pipe dtor won't close it, and
241 // return it
242 HANDLE Detach(Direction which)
243 {
79066131
VZ
244 HANDLE handle = m_handles[which];
245 m_handles[which] = INVALID_HANDLE_VALUE;
246
247 return handle;
248 }
249
250 // close the pipe descriptors
251 void Close()
252 {
253 for ( size_t n = 0; n < WXSIZEOF(m_handles); n++ )
254 {
255 if ( m_handles[n] != INVALID_HANDLE_VALUE )
256 {
257 ::CloseHandle(m_handles[n]);
258 m_handles[n] = INVALID_HANDLE_VALUE;
259 }
260 }
261 }
262
263 // dtor closes the pipe descriptors
264 ~wxPipe() { Close(); }
265
266private:
267 HANDLE m_handles[2];
268};
269
270#endif // wxUSE_STREAMS
271
272// ============================================================================
273// implementation
274// ============================================================================
275
79066131
VZ
276// ----------------------------------------------------------------------------
277// process termination detecting support
278// ----------------------------------------------------------------------------
279
280// thread function for the thread monitoring the process termination
281static DWORD __stdcall wxExecuteThread(void *arg)
282{
45d5a0c6 283 wxExecuteData * const data = (wxExecuteData *)arg;
79066131
VZ
284
285 if ( ::WaitForSingleObject(data->hProcess, INFINITE) != WAIT_OBJECT_0 )
286 {
287 wxLogDebug(_T("Waiting for the process termination failed!"));
288 }
289
290 // get the exit code
291 if ( !::GetExitCodeProcess(data->hProcess, &data->dwExitCode) )
292 {
293 wxLogLastError(wxT("GetExitCodeProcess"));
294 }
295
296 wxASSERT_MSG( data->dwExitCode != STILL_ACTIVE,
297 wxT("process should have terminated") );
298
299 // send a message indicating process termination to the window
300 ::SendMessage(data->hWnd, wxWM_PROC_TERMINATED, 0, (LPARAM)data);
301
302 return 0;
303}
304
305// window procedure of a hidden window which is created just to receive
306// the notification message when a process exits
307LRESULT APIENTRY _EXPORT wxExecuteWindowCbk(HWND hWnd, UINT message,
308 WPARAM wParam, LPARAM lParam)
309{
310 if ( message == wxWM_PROC_TERMINATED )
311 {
312 DestroyWindow(hWnd); // we don't need it any more
313
45d5a0c6 314 wxExecuteData * const data = (wxExecuteData *)lParam;
79066131
VZ
315 if ( data->handler )
316 {
317 data->handler->OnTerminate((int)data->dwProcessId,
318 (int)data->dwExitCode);
319 }
320
321 if ( data->state )
322 {
323 // we're executing synchronously, tell the waiting thread
324 // that the process finished
325 data->state = 0;
326 }
327 else
328 {
329 // asynchronous execution - we should do the clean up
330 delete data;
331 }
332
333 return 0;
334 }
335 else
336 {
45d5a0c6 337 return ::DefWindowProc(hWnd, message, wParam, lParam);
79066131
VZ
338 }
339}
340
341// ============================================================================
342// implementation of IO redirection support classes
343// ============================================================================
344
4676948b 345#if wxUSE_STREAMS && !defined(__WXWINCE__)
79066131
VZ
346
347// ----------------------------------------------------------------------------
348// wxPipeInputStreams
349// ----------------------------------------------------------------------------
8b33ae2d
GL
350
351wxPipeInputStream::wxPipeInputStream(HANDLE hInput)
352{
353 m_hInput = hInput;
cd6ce4a9 354}
8b33ae2d
GL
355
356wxPipeInputStream::~wxPipeInputStream()
357{
79066131
VZ
358 if ( m_hInput != INVALID_HANDLE_VALUE )
359 ::CloseHandle(m_hInput);
8b33ae2d
GL
360}
361
2b5f62a0 362bool wxPipeInputStream::CanRead() const
8b33ae2d 363{
79066131 364 if ( !IsOpened() )
27d2dbbc 365 return false;
79066131 366
f6bcfd97
BP
367 DWORD nAvailable;
368
369 // function name is misleading, it works with anon pipes as well
370 DWORD rc = ::PeekNamedPipe
371 (
372 m_hInput, // handle
373 NULL, 0, // ptr to buffer and its size
374 NULL, // [out] bytes read
375 &nAvailable, // [out] bytes available
376 NULL // [out] bytes left
377 );
378
379 if ( !rc )
380 {
381 if ( ::GetLastError() != ERROR_BROKEN_PIPE )
382 {
383 // unexpected error
384 wxLogLastError(_T("PeekNamedPipe"));
385 }
8b33ae2d 386
f6bcfd97
BP
387 // don't try to continue reading from a pipe if an error occured or if
388 // it had been closed
79066131
VZ
389 ::CloseHandle(m_hInput);
390
2b5f62a0 391 wxPipeInputStream *self = wxConstCast(this, wxPipeInputStream);
79066131 392
2b5f62a0
VZ
393 self->m_hInput = INVALID_HANDLE_VALUE;
394 self->m_lasterror = wxSTREAM_EOF;
395
396 nAvailable = 0;
f6bcfd97 397 }
79066131
VZ
398
399 return nAvailable != 0;
f6bcfd97
BP
400}
401
402size_t wxPipeInputStream::OnSysRead(void *buffer, size_t len)
403{
2b5f62a0 404 if ( !IsOpened() )
79066131
VZ
405 {
406 m_lasterror = wxSTREAM_EOF;
407
f6bcfd97 408 return 0;
79066131
VZ
409 }
410
f6bcfd97
BP
411 DWORD bytesRead;
412 if ( !::ReadFile(m_hInput, buffer, len, &bytesRead, NULL) )
413 {
2b5f62a0
VZ
414 m_lasterror = ::GetLastError() == ERROR_BROKEN_PIPE
415 ? wxSTREAM_EOF
416 : wxSTREAM_READ_ERROR;
8b33ae2d 417 }
f6bcfd97 418
2b5f62a0 419 // bytesRead is set to 0, as desired, if an error occured
8b33ae2d
GL
420 return bytesRead;
421}
422
79066131 423// ----------------------------------------------------------------------------
8b33ae2d 424// wxPipeOutputStream
79066131 425// ----------------------------------------------------------------------------
8b33ae2d
GL
426
427wxPipeOutputStream::wxPipeOutputStream(HANDLE hOutput)
428{
429 m_hOutput = hOutput;
3338a5bd
VZ
430
431 // unblock the pipe to prevent deadlocks when we're writing to the pipe
432 // from which the child process can't read because it is writing in its own
433 // end of it
434 DWORD mode = PIPE_READMODE_BYTE | PIPE_NOWAIT;
435 if ( !::SetNamedPipeHandleState
436 (
437 m_hOutput,
438 &mode,
439 NULL, // collection count (we don't set it)
440 NULL // timeout (we don't set it neither)
441 ) )
442 {
443 wxLogLastError(_T("SetNamedPipeHandleState(PIPE_NOWAIT)"));
444 }
cd6ce4a9 445}
8b33ae2d
GL
446
447wxPipeOutputStream::~wxPipeOutputStream()
448{
449 ::CloseHandle(m_hOutput);
450}
451
452size_t wxPipeOutputStream::OnSysWrite(const void *buffer, size_t len)
453{
2b5f62a0 454 m_lasterror = wxSTREAM_NO_ERROR;
3338a5bd
VZ
455
456 DWORD totalWritten = 0;
457 while ( len > 0 )
f6bcfd97 458 {
3338a5bd
VZ
459 DWORD chunkWritten;
460 if ( !::WriteFile(m_hOutput, buffer, len, &chunkWritten, NULL) )
461 {
462 m_lasterror = ::GetLastError() == ERROR_BROKEN_PIPE
463 ? wxSTREAM_EOF
464 : wxSTREAM_WRITE_ERROR;
465 break;
466 }
467
468 if ( !chunkWritten )
469 break;
470
471 buffer = (char *)buffer + chunkWritten;
472 totalWritten += chunkWritten;
473 len -= chunkWritten;
8b33ae2d 474 }
f6bcfd97 475
3338a5bd 476 return totalWritten;
8b33ae2d
GL
477}
478
79066131
VZ
479#endif // wxUSE_STREAMS
480
b568d04f 481// ============================================================================
79066131 482// wxExecute functions family
b568d04f 483// ============================================================================
5260b1c5 484
ca289436
VZ
485#if wxUSE_IPC
486
487// connect to the given server via DDE and ask it to execute the command
488static bool wxExecuteDDE(const wxString& ddeServer,
489 const wxString& ddeTopic,
490 const wxString& ddeCommand)
491{
999836aa 492 bool ok wxDUMMY_INITIALIZE(false);
ca289436
VZ
493
494 wxDDEClient client;
fda7962d 495 wxConnectionBase *conn = client.MakeConnection(wxEmptyString,
ca289436
VZ
496 ddeServer,
497 ddeTopic);
498 if ( !conn )
499 {
27d2dbbc 500 ok = false;
ca289436
VZ
501 }
502 else // connected to DDE server
503 {
4dd03db9
VZ
504 // the added complication here is that although most programs use
505 // XTYP_EXECUTE for their DDE API, some important ones -- like Word
506 // and other MS stuff - use XTYP_REQUEST!
ca289436 507 //
4dd03db9
VZ
508 // moreover, anotheri mportant program (IE) understands both but
509 // returns an error from Execute() so we must try Request() first
510 // to avoid doing it twice
ca289436 511 {
4dd03db9 512 // we're prepared for this one to fail, so don't show errors
ca289436 513 wxLogNull noErrors;
4dd03db9
VZ
514
515 ok = conn->Request(ddeCommand) != NULL;
ca289436
VZ
516 }
517
518 if ( !ok )
519 {
4dd03db9
VZ
520 // now try execute -- but show the errors
521 ok = conn->Execute(ddeCommand);
ca289436
VZ
522 }
523 }
524
525 return ok;
526}
527
528#endif // wxUSE_IPC
529
fbf456aa 530long wxExecute(const wxString& cmd, int flags, wxProcess *handler)
32592631 531{
27d2dbbc 532 wxCHECK_MSG( !cmd.IsEmpty(), 0, wxT("empty command in wxExecute") );
5bd3a2da 533
647b8e37
VZ
534#if wxUSE_THREADS
535 // for many reasons, the code below breaks down if it's called from another
536 // thread -- this could be fixed, but as Unix versions don't support this
537 // neither I don't want to waste time on this now
538 wxASSERT_MSG( wxThread::IsMain(),
539 _T("wxExecute() can be called only from the main thread") );
540#endif // wxUSE_THREADS
541
039f62f4 542 wxString command;
6ba63600 543
731dd422 544#if wxUSE_IPC
5bd3a2da
VZ
545 // DDE hack: this is really not pretty, but we need to allow this for
546 // transparent handling of DDE servers in wxMimeTypesManager. Usually it
547 // returns the command which should be run to view/open/... a file of the
548 // given type. Sometimes, however, this command just launches the server
549 // and an additional DDE request must be made to really open the file. To
550 // keep all this well hidden from the application, we allow a special form
6ba63600 551 // of command: WX_DDE#<command>#DDE_SERVER#DDE_TOPIC#DDE_COMMAND in which
5bd3a2da 552 // case we execute just <command> and process the rest below
039f62f4 553 wxString ddeServer, ddeTopic, ddeCommand;
5bd3a2da
VZ
554 static const size_t lenDdePrefix = 7; // strlen("WX_DDE:")
555 if ( cmd.Left(lenDdePrefix) == _T("WX_DDE#") )
556 {
ca289436
VZ
557 // speed up the concatenations below
558 ddeServer.reserve(256);
559 ddeTopic.reserve(256);
560 ddeCommand.reserve(256);
561
5bd3a2da
VZ
562 const wxChar *p = cmd.c_str() + 7;
563 while ( *p && *p != _T('#') )
564 {
565 command += *p++;
566 }
567
568 if ( *p )
569 {
570 // skip '#'
571 p++;
572 }
573 else
574 {
575 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
576 }
577
578 while ( *p && *p != _T('#') )
579 {
580 ddeServer += *p++;
581 }
582
583 if ( *p )
584 {
585 // skip '#'
586 p++;
587 }
588 else
589 {
590 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
591 }
592
593 while ( *p && *p != _T('#') )
594 {
595 ddeTopic += *p++;
596 }
597
598 if ( *p )
599 {
600 // skip '#'
601 p++;
602 }
603 else
604 {
605 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
606 }
607
608 while ( *p )
609 {
610 ddeCommand += *p++;
611 }
6ba63600 612
ca289436
VZ
613 // if we want to just launch the program and not wait for its
614 // termination, try to execute DDE command right now, it can succeed if
615 // the process is already running - but as it fails if it's not
616 // running, suppress any errors it might generate
fbf456aa 617 if ( !(flags & wxEXEC_SYNC) )
6ba63600 618 {
ca289436
VZ
619 wxLogNull noErrors;
620 if ( wxExecuteDDE(ddeServer, ddeTopic, ddeCommand) )
621 {
622 // a dummy PID - this is a hack, of course, but it's well worth
623 // it as we don't open a new server each time we're called
624 // which would be quite bad
625 return -1;
626 }
6ba63600 627 }
5bd3a2da
VZ
628 }
629 else
731dd422 630#endif // wxUSE_IPC
5bd3a2da
VZ
631 {
632 // no DDE
633 command = cmd;
634 }
32592631 635
f6bcfd97
BP
636 // the IO redirection is only supported with wxUSE_STREAMS
637 BOOL redirect = FALSE;
79066131 638
4676948b 639#if wxUSE_STREAMS && !defined(__WXWINCE__)
79066131
VZ
640 wxPipe pipeIn, pipeOut, pipeErr;
641
642 // we'll save here the copy of pipeIn[Write]
33ac7e6f 643 HANDLE hpipeStdinWrite = INVALID_HANDLE_VALUE;
8b33ae2d 644
cd6ce4a9 645 // open the pipes to which child process IO will be redirected if needed
cd6ce4a9
VZ
646 if ( handler && handler->IsRedirected() )
647 {
79066131
VZ
648 // create pipes for redirecting stdin, stdout and stderr
649 if ( !pipeIn.Create() || !pipeOut.Create() || !pipeErr.Create() )
cd6ce4a9 650 {
79066131 651 wxLogSysError(_("Failed to redirect the child process IO"));
8b33ae2d 652
fbf456aa
VZ
653 // indicate failure: we need to return different error code
654 // depending on the sync flag
655 return flags & wxEXEC_SYNC ? -1 : 0;
8b33ae2d
GL
656 }
657
f6bcfd97 658 redirect = TRUE;
8b33ae2d 659 }
f6bcfd97 660#endif // wxUSE_STREAMS
5bd3a2da 661
cb6827a8
VZ
662 // create the process
663 STARTUPINFO si;
11c7d5b6 664 wxZeroMemory(si);
cb6827a8
VZ
665 si.cb = sizeof(si);
666
4676948b 667#if wxUSE_STREAMS && !defined(__WXWINCE__)
f6bcfd97 668 if ( redirect )
cb6827a8 669 {
fbf456aa 670 si.dwFlags = STARTF_USESTDHANDLES;
f6bcfd97 671
79066131
VZ
672 si.hStdInput = pipeIn[wxPipe::Read];
673 si.hStdOutput = pipeOut[wxPipe::Write];
674 si.hStdError = pipeErr[wxPipe::Write];
f6bcfd97 675
fbf456aa
VZ
676 // when the std IO is redirected, we don't show the (console) process
677 // window by default, but this can be overridden by the caller by
678 // specifying wxEXEC_NOHIDE flag
679 if ( !(flags & wxEXEC_NOHIDE) )
680 {
681 si.dwFlags |= STARTF_USESHOWWINDOW;
682 si.wShowWindow = SW_HIDE;
683 }
f6bcfd97
BP
684
685 // we must duplicate the handle to the write side of stdin pipe to make
79066131
VZ
686 // it non inheritable: indeed, we must close the writing end of pipeIn
687 // before launching the child process as otherwise this handle will be
f6bcfd97
BP
688 // inherited by the child which will never close it and so the pipe
689 // will never be closed and the child will be left stuck in ReadFile()
79066131 690 HANDLE pipeInWrite = pipeIn.Detach(wxPipe::Write);
f6bcfd97
BP
691 if ( !::DuplicateHandle
692 (
79066131
VZ
693 ::GetCurrentProcess(),
694 pipeInWrite,
695 ::GetCurrentProcess(),
f6bcfd97
BP
696 &hpipeStdinWrite,
697 0, // desired access: unused here
698 FALSE, // not inherited
699 DUPLICATE_SAME_ACCESS // same access as for src handle
700 ) )
cd6ce4a9 701 {
f6bcfd97 702 wxLogLastError(_T("DuplicateHandle"));
8b33ae2d 703 }
cd6ce4a9 704
79066131 705 ::CloseHandle(pipeInWrite);
f6bcfd97
BP
706 }
707#endif // wxUSE_STREAMS
cb6827a8 708
f6bcfd97 709 PROCESS_INFORMATION pi;
4676948b
JS
710 DWORD dwFlags = CREATE_SUSPENDED;
711#ifndef __WXWINCE__
712 dwFlags |= CREATE_DEFAULT_ERROR_MODE ;
713#endif
f6bcfd97
BP
714
715 bool ok = ::CreateProcess
716 (
717 NULL, // application name (use only cmd line)
718 (wxChar *)
719 command.c_str(), // full command line
720 NULL, // security attributes: defaults for both
721 NULL, // the process and its main thread
722 redirect, // inherit handles if we use pipes
723 dwFlags, // process creation flags
724 NULL, // environment (use the same)
725 NULL, // current directory (use the same)
726 &si, // startup info (unused here)
727 &pi // process info
728 ) != 0;
729
4676948b 730#if wxUSE_STREAMS && !defined(__WXWINCE__)
f6bcfd97
BP
731 // we can close the pipe ends used by child anyhow
732 if ( redirect )
733 {
79066131
VZ
734 ::CloseHandle(pipeIn.Detach(wxPipe::Read));
735 ::CloseHandle(pipeOut.Detach(wxPipe::Write));
736 ::CloseHandle(pipeErr.Detach(wxPipe::Write));
cb6827a8 737 }
f6bcfd97 738#endif // wxUSE_STREAMS
cb6827a8 739
f6bcfd97 740 if ( !ok )
5e1febfa 741 {
4676948b 742#if wxUSE_STREAMS && !defined(__WXWINCE__)
f6bcfd97
BP
743 // close the other handles too
744 if ( redirect )
5e1febfa 745 {
79066131
VZ
746 ::CloseHandle(pipeOut.Detach(wxPipe::Read));
747 ::CloseHandle(pipeErr.Detach(wxPipe::Read));
5e1febfa 748 }
f6bcfd97 749#endif // wxUSE_STREAMS
5e1febfa 750
f6bcfd97
BP
751 wxLogSysError(_("Execution of command '%s' failed"), command.c_str());
752
fbf456aa 753 return flags & wxEXEC_SYNC ? -1 : 0;
f6bcfd97 754 }
8b33ae2d 755
4676948b 756#if wxUSE_STREAMS && !defined(__WXWINCE__)
79066131
VZ
757 // the input buffer bufOut is connected to stdout, this is why it is
758 // called bufOut and not bufIn
759 wxStreamTempInputBuffer bufOut,
760 bufErr;
761
f6bcfd97
BP
762 if ( redirect )
763 {
8b33ae2d 764 // We can now initialize the wxStreams
79066131
VZ
765 wxPipeInputStream *
766 outStream = new wxPipeInputStream(pipeOut.Detach(wxPipe::Read));
767 wxPipeInputStream *
768 errStream = new wxPipeInputStream(pipeErr.Detach(wxPipe::Read));
769 wxPipeOutputStream *
770 inStream = new wxPipeOutputStream(hpipeStdinWrite);
771
772 handler->SetPipeStreams(outStream, inStream, errStream);
8b33ae2d 773
79066131
VZ
774 bufOut.Init(outStream);
775 bufErr.Init(errStream);
8b33ae2d 776 }
f6bcfd97 777#endif // wxUSE_STREAMS
8b33ae2d 778
cb6827a8
VZ
779 // create a hidden window to receive notification about process
780 // termination
eccd1992
VZ
781 HWND hwnd = wxCreateHiddenWindow
782 (
783 &gs_classForHiddenWindow,
784 wxMSWEXEC_WNDCLASSNAME,
785 (WNDPROC)wxExecuteWindowCbk
786 );
787
223d09f6 788 wxASSERT_MSG( hwnd, wxT("can't create a hidden window for wxExecute") );
e6045e08 789
cb6827a8
VZ
790 // Alloc data
791 wxExecuteData *data = new wxExecuteData;
792 data->hProcess = pi.hProcess;
793 data->dwProcessId = pi.dwProcessId;
794 data->hWnd = hwnd;
fbf456aa
VZ
795 data->state = (flags & wxEXEC_SYNC) != 0;
796 if ( flags & wxEXEC_SYNC )
e6045e08 797 {
5e1febfa
VZ
798 // handler may be !NULL for capturing program output, but we don't use
799 // it wxExecuteData struct in this case
e6045e08
VZ
800 data->handler = NULL;
801 }
802 else
803 {
804 // may be NULL or not
805 data->handler = handler;
806 }
cb6827a8
VZ
807
808 DWORD tid;
809 HANDLE hThread = ::CreateThread(NULL,
810 0,
19193a2c 811 wxExecuteThread,
cb6827a8
VZ
812 (void *)data,
813 0,
814 &tid);
815
0d7ea902
VZ
816 // resume process we created now - whether the thread creation succeeded or
817 // not
818 if ( ::ResumeThread(pi.hThread) == (DWORD)-1 )
819 {
820 // ignore it - what can we do?
f6bcfd97 821 wxLogLastError(wxT("ResumeThread in wxExecute"));
0d7ea902
VZ
822 }
823
824 // close unneeded handle
825 if ( !::CloseHandle(pi.hThread) )
f6bcfd97 826 wxLogLastError(wxT("CloseHandle(hThread)"));
0d7ea902 827
cb6827a8
VZ
828 if ( !hThread )
829 {
f6bcfd97 830 wxLogLastError(wxT("CreateThread in wxExecute"));
cb6827a8
VZ
831
832 DestroyWindow(hwnd);
833 delete data;
834
835 // the process still started up successfully...
836 return pi.dwProcessId;
837 }
e6045e08 838
f6bcfd97
BP
839 ::CloseHandle(hThread);
840
4676948b 841#if wxUSE_IPC && !defined(__WXWINCE__)
5bd3a2da
VZ
842 // second part of DDE hack: now establish the DDE conversation with the
843 // just launched process
ca289436 844 if ( !ddeServer.empty() )
5bd3a2da 845 {
ca289436
VZ
846 bool ok;
847
848 // give the process the time to init itself
849 //
850 // we use a very big timeout hoping that WaitForInputIdle() will return
851 // much sooner, but not INFINITE just in case the process hangs
852 // completely - like this we will regain control sooner or later
853 switch ( ::WaitForInputIdle(pi.hProcess, 10000 /* 10 seconds */) )
6ba63600 854 {
ca289436
VZ
855 default:
856 wxFAIL_MSG( _T("unexpected WaitForInputIdle() return code") );
857 // fall through
6ba63600 858
ca289436
VZ
859 case -1:
860 wxLogLastError(_T("WaitForInputIdle() in wxExecute"));
6ba63600 861
ca289436
VZ
862 case WAIT_TIMEOUT:
863 wxLogDebug(_T("Timeout too small in WaitForInputIdle"));
864
27d2dbbc 865 ok = false;
ca289436
VZ
866 break;
867
868 case 0:
869 // ok, process ready to accept DDE requests
870 ok = wxExecuteDDE(ddeServer, ddeTopic, ddeCommand);
6ba63600 871 }
1b47bebc
VZ
872
873 if ( !ok )
874 {
875 wxLogDebug(_T("Failed to send DDE request to the process \"%s\"."),
876 cmd.c_str());
877 }
5bd3a2da 878 }
731dd422 879#endif // wxUSE_IPC
5bd3a2da 880
fbf456aa 881 if ( !(flags & wxEXEC_SYNC) )
cb6827a8
VZ
882 {
883 // clean up will be done when the process terminates
e6045e08
VZ
884
885 // return the pid
cb6827a8
VZ
886 return pi.dwProcessId;
887 }
e6045e08 888
e2478fde
VZ
889 wxAppTraits *traits = wxTheApp ? wxTheApp->GetTraits() : NULL;
890 wxCHECK_MSG( traits, -1, _T("no wxAppTraits in wxExecute()?") );
891
068a7cfe 892 // disable all app windows while waiting for the child process to finish
e2478fde
VZ
893 void *cookie = traits->BeforeChildWaitLoop();
894
895 // wait until the child process terminates
896 while ( data->state )
897 {
4676948b 898#if wxUSE_STREAMS && !defined(__WXWINCE__)
e2478fde
VZ
899 bufOut.Update();
900 bufErr.Update();
79066131
VZ
901#endif // wxUSE_STREAMS
902
e2478fde
VZ
903 // don't eat 100% of the CPU -- ugly but anything else requires
904 // real async IO which we don't have for the moment
905 ::Sleep(50);
e6045e08 906
e2478fde
VZ
907 // we must process messages or we'd never get wxWM_PROC_TERMINATED
908 traits->AlwaysYield();
cd6ce4a9 909 }
068a7cfe 910
e2478fde 911 traits->AfterChildWaitLoop(cookie);
0d7ea902 912
e6045e08 913 DWORD dwExitCode = data->dwExitCode;
cb6827a8
VZ
914 delete data;
915
e6045e08
VZ
916 // return the exit code
917 return dwExitCode;
32592631 918}
c740f496 919
0493ba13 920long wxExecute(wxChar **argv, int flags, wxProcess *handler)
c740f496 921{
cb6827a8 922 wxString command;
e6045e08 923
0493ba13 924 for ( ;; )
cb6827a8 925 {
0493ba13
VZ
926 command += *argv++;
927 if ( !*argv )
928 break;
cb6827a8 929
0493ba13
VZ
930 command += _T(' ');
931 }
cb6827a8 932
fbf456aa 933 return wxExecute(command, flags, handler);
c740f496 934}
006162a9 935