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