]> git.saurik.com Git - wxWidgets.git/blob - src/msw/utilsexc.cpp
Handle terminating NULL correctly
[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 wxWidgets 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 if ( !::CloseHandle(hProcess) )
117 {
118 wxLogLastError(wxT("CloseHandle(hProcess)"));
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
127 bool state; // set to FALSE when the process finishes
128 };
129
130 class wxExecuteModule : public wxModule
131 {
132 public:
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
147 private:
148 DECLARE_DYNAMIC_CLASS(wxExecuteModule)
149 };
150
151 #if wxUSE_STREAMS && !defined(__WXWINCE__)
152
153 // ----------------------------------------------------------------------------
154 // wxPipeStreams
155 // ----------------------------------------------------------------------------
156
157 class wxPipeInputStream: public wxInputStream
158 {
159 public:
160 wxPipeInputStream(HANDLE hInput);
161 virtual ~wxPipeInputStream();
162
163 // returns TRUE if the pipe is still opened
164 bool IsOpened() const { return m_hInput != INVALID_HANDLE_VALUE; }
165
166 // returns TRUE if there is any data to be read from the pipe
167 virtual bool CanRead() const;
168
169 protected:
170 size_t OnSysRead(void *buffer, size_t len);
171
172 protected:
173 HANDLE m_hInput;
174
175 DECLARE_NO_COPY_CLASS(wxPipeInputStream)
176 };
177
178 class wxPipeOutputStream: public wxOutputStream
179 {
180 public:
181 wxPipeOutputStream(HANDLE hOutput);
182 virtual ~wxPipeOutputStream();
183
184 protected:
185 size_t OnSysWrite(const void *buffer, size_t len);
186
187 protected:
188 HANDLE m_hOutput;
189
190 DECLARE_NO_COPY_CLASS(wxPipeOutputStream)
191 };
192
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
201 class wxPipe
202 {
203 public:
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
214 // create the pipe, return TRUE if ok, FALSE on error
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
228 return FALSE;
229 }
230
231 return TRUE;
232 }
233
234 // return TRUE if we were created successfully
235 bool IsOk() const { return m_handles[Read] != INVALID_HANDLE_VALUE; }
236
237 // return the descriptor for one of the pipe ends
238 HANDLE operator[](Direction which) const { return m_handles[which]; }
239
240 // detach a descriptor, meaning that the pipe dtor won't close it, and
241 // return it
242 HANDLE Detach(Direction which)
243 {
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
266 private:
267 HANDLE m_handles[2];
268 };
269
270 #endif // wxUSE_STREAMS
271
272 // ============================================================================
273 // implementation
274 // ============================================================================
275
276 // ----------------------------------------------------------------------------
277 // process termination detecting support
278 // ----------------------------------------------------------------------------
279
280 // thread function for the thread monitoring the process termination
281 static DWORD __stdcall wxExecuteThread(void *arg)
282 {
283 wxExecuteData * const data = (wxExecuteData *)arg;
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
307 LRESULT 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
314 wxExecuteData * const data = (wxExecuteData *)lParam;
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 {
337 return ::DefWindowProc(hWnd, message, wParam, lParam);
338 }
339 }
340
341 // ============================================================================
342 // implementation of IO redirection support classes
343 // ============================================================================
344
345 #if wxUSE_STREAMS && !defined(__WXWINCE__)
346
347 // ----------------------------------------------------------------------------
348 // wxPipeInputStreams
349 // ----------------------------------------------------------------------------
350
351 wxPipeInputStream::wxPipeInputStream(HANDLE hInput)
352 {
353 m_hInput = hInput;
354 }
355
356 wxPipeInputStream::~wxPipeInputStream()
357 {
358 if ( m_hInput != INVALID_HANDLE_VALUE )
359 ::CloseHandle(m_hInput);
360 }
361
362 bool wxPipeInputStream::CanRead() const
363 {
364 if ( !IsOpened() )
365 return FALSE;
366
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 }
386
387 // don't try to continue reading from a pipe if an error occured or if
388 // it had been closed
389 ::CloseHandle(m_hInput);
390
391 wxPipeInputStream *self = wxConstCast(this, wxPipeInputStream);
392
393 self->m_hInput = INVALID_HANDLE_VALUE;
394 self->m_lasterror = wxSTREAM_EOF;
395
396 nAvailable = 0;
397 }
398
399 return nAvailable != 0;
400 }
401
402 size_t wxPipeInputStream::OnSysRead(void *buffer, size_t len)
403 {
404 if ( !IsOpened() )
405 {
406 m_lasterror = wxSTREAM_EOF;
407
408 return 0;
409 }
410
411 DWORD bytesRead;
412 if ( !::ReadFile(m_hInput, buffer, len, &bytesRead, NULL) )
413 {
414 m_lasterror = ::GetLastError() == ERROR_BROKEN_PIPE
415 ? wxSTREAM_EOF
416 : wxSTREAM_READ_ERROR;
417 }
418
419 // bytesRead is set to 0, as desired, if an error occured
420 return bytesRead;
421 }
422
423 // ----------------------------------------------------------------------------
424 // wxPipeOutputStream
425 // ----------------------------------------------------------------------------
426
427 wxPipeOutputStream::wxPipeOutputStream(HANDLE hOutput)
428 {
429 m_hOutput = hOutput;
430 }
431
432 wxPipeOutputStream::~wxPipeOutputStream()
433 {
434 ::CloseHandle(m_hOutput);
435 }
436
437 size_t wxPipeOutputStream::OnSysWrite(const void *buffer, size_t len)
438 {
439 DWORD bytesWritten;
440
441 m_lasterror = wxSTREAM_NO_ERROR;
442 if ( !::WriteFile(m_hOutput, buffer, len, &bytesWritten, NULL) )
443 {
444 m_lasterror = ::GetLastError() == ERROR_BROKEN_PIPE
445 ? wxSTREAM_EOF
446 : wxSTREAM_WRITE_ERROR;
447 }
448
449 return bytesWritten;
450 }
451
452 #endif // wxUSE_STREAMS
453
454 // ============================================================================
455 // wxExecute functions family
456 // ============================================================================
457
458 #if wxUSE_IPC
459
460 // connect to the given server via DDE and ask it to execute the command
461 static bool wxExecuteDDE(const wxString& ddeServer,
462 const wxString& ddeTopic,
463 const wxString& ddeCommand)
464 {
465 bool ok wxDUMMY_INITIALIZE(false);
466
467 wxDDEClient client;
468 wxConnectionBase *conn = client.MakeConnection(wxEmptyString,
469 ddeServer,
470 ddeTopic);
471 if ( !conn )
472 {
473 ok = FALSE;
474 }
475 else // connected to DDE server
476 {
477 // the added complication here is that although most programs use
478 // XTYP_EXECUTE for their DDE API, some important ones -- like Word
479 // and other MS stuff - use XTYP_REQUEST!
480 //
481 // moreover, anotheri mportant program (IE) understands both but
482 // returns an error from Execute() so we must try Request() first
483 // to avoid doing it twice
484 {
485 // we're prepared for this one to fail, so don't show errors
486 wxLogNull noErrors;
487
488 ok = conn->Request(ddeCommand) != NULL;
489 }
490
491 if ( !ok )
492 {
493 // now try execute -- but show the errors
494 ok = conn->Execute(ddeCommand);
495 }
496 }
497
498 return ok;
499 }
500
501 #endif // wxUSE_IPC
502
503 long wxExecute(const wxString& cmd, int flags, wxProcess *handler)
504 {
505 wxCHECK_MSG( !!cmd, 0, wxT("empty command in wxExecute") );
506
507 #if wxUSE_THREADS
508 // for many reasons, the code below breaks down if it's called from another
509 // thread -- this could be fixed, but as Unix versions don't support this
510 // neither I don't want to waste time on this now
511 wxASSERT_MSG( wxThread::IsMain(),
512 _T("wxExecute() can be called only from the main thread") );
513 #endif // wxUSE_THREADS
514
515 wxString command;
516
517 #if wxUSE_IPC
518 // DDE hack: this is really not pretty, but we need to allow this for
519 // transparent handling of DDE servers in wxMimeTypesManager. Usually it
520 // returns the command which should be run to view/open/... a file of the
521 // given type. Sometimes, however, this command just launches the server
522 // and an additional DDE request must be made to really open the file. To
523 // keep all this well hidden from the application, we allow a special form
524 // of command: WX_DDE#<command>#DDE_SERVER#DDE_TOPIC#DDE_COMMAND in which
525 // case we execute just <command> and process the rest below
526 wxString ddeServer, ddeTopic, ddeCommand;
527 static const size_t lenDdePrefix = 7; // strlen("WX_DDE:")
528 if ( cmd.Left(lenDdePrefix) == _T("WX_DDE#") )
529 {
530 // speed up the concatenations below
531 ddeServer.reserve(256);
532 ddeTopic.reserve(256);
533 ddeCommand.reserve(256);
534
535 const wxChar *p = cmd.c_str() + 7;
536 while ( *p && *p != _T('#') )
537 {
538 command += *p++;
539 }
540
541 if ( *p )
542 {
543 // skip '#'
544 p++;
545 }
546 else
547 {
548 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
549 }
550
551 while ( *p && *p != _T('#') )
552 {
553 ddeServer += *p++;
554 }
555
556 if ( *p )
557 {
558 // skip '#'
559 p++;
560 }
561 else
562 {
563 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
564 }
565
566 while ( *p && *p != _T('#') )
567 {
568 ddeTopic += *p++;
569 }
570
571 if ( *p )
572 {
573 // skip '#'
574 p++;
575 }
576 else
577 {
578 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
579 }
580
581 while ( *p )
582 {
583 ddeCommand += *p++;
584 }
585
586 // if we want to just launch the program and not wait for its
587 // termination, try to execute DDE command right now, it can succeed if
588 // the process is already running - but as it fails if it's not
589 // running, suppress any errors it might generate
590 if ( !(flags & wxEXEC_SYNC) )
591 {
592 wxLogNull noErrors;
593 if ( wxExecuteDDE(ddeServer, ddeTopic, ddeCommand) )
594 {
595 // a dummy PID - this is a hack, of course, but it's well worth
596 // it as we don't open a new server each time we're called
597 // which would be quite bad
598 return -1;
599 }
600 }
601 }
602 else
603 #endif // wxUSE_IPC
604 {
605 // no DDE
606 command = cmd;
607 }
608
609 // the IO redirection is only supported with wxUSE_STREAMS
610 BOOL redirect = FALSE;
611
612 #if wxUSE_STREAMS && !defined(__WXWINCE__)
613 wxPipe pipeIn, pipeOut, pipeErr;
614
615 // we'll save here the copy of pipeIn[Write]
616 HANDLE hpipeStdinWrite = INVALID_HANDLE_VALUE;
617
618 // open the pipes to which child process IO will be redirected if needed
619 if ( handler && handler->IsRedirected() )
620 {
621 // create pipes for redirecting stdin, stdout and stderr
622 if ( !pipeIn.Create() || !pipeOut.Create() || !pipeErr.Create() )
623 {
624 wxLogSysError(_("Failed to redirect the child process IO"));
625
626 // indicate failure: we need to return different error code
627 // depending on the sync flag
628 return flags & wxEXEC_SYNC ? -1 : 0;
629 }
630
631 redirect = TRUE;
632 }
633 #endif // wxUSE_STREAMS
634
635 // create the process
636 STARTUPINFO si;
637 wxZeroMemory(si);
638 si.cb = sizeof(si);
639
640 #if wxUSE_STREAMS && !defined(__WXWINCE__)
641 if ( redirect )
642 {
643 si.dwFlags = STARTF_USESTDHANDLES;
644
645 si.hStdInput = pipeIn[wxPipe::Read];
646 si.hStdOutput = pipeOut[wxPipe::Write];
647 si.hStdError = pipeErr[wxPipe::Write];
648
649 // when the std IO is redirected, we don't show the (console) process
650 // window by default, but this can be overridden by the caller by
651 // specifying wxEXEC_NOHIDE flag
652 if ( !(flags & wxEXEC_NOHIDE) )
653 {
654 si.dwFlags |= STARTF_USESHOWWINDOW;
655 si.wShowWindow = SW_HIDE;
656 }
657
658 // we must duplicate the handle to the write side of stdin pipe to make
659 // it non inheritable: indeed, we must close the writing end of pipeIn
660 // before launching the child process as otherwise this handle will be
661 // inherited by the child which will never close it and so the pipe
662 // will never be closed and the child will be left stuck in ReadFile()
663 HANDLE pipeInWrite = pipeIn.Detach(wxPipe::Write);
664 if ( !::DuplicateHandle
665 (
666 ::GetCurrentProcess(),
667 pipeInWrite,
668 ::GetCurrentProcess(),
669 &hpipeStdinWrite,
670 0, // desired access: unused here
671 FALSE, // not inherited
672 DUPLICATE_SAME_ACCESS // same access as for src handle
673 ) )
674 {
675 wxLogLastError(_T("DuplicateHandle"));
676 }
677
678 ::CloseHandle(pipeInWrite);
679 }
680 #endif // wxUSE_STREAMS
681
682 PROCESS_INFORMATION pi;
683 DWORD dwFlags = CREATE_SUSPENDED;
684 #ifndef __WXWINCE__
685 dwFlags |= CREATE_DEFAULT_ERROR_MODE ;
686 #endif
687
688 bool ok = ::CreateProcess
689 (
690 NULL, // application name (use only cmd line)
691 (wxChar *)
692 command.c_str(), // full command line
693 NULL, // security attributes: defaults for both
694 NULL, // the process and its main thread
695 redirect, // inherit handles if we use pipes
696 dwFlags, // process creation flags
697 NULL, // environment (use the same)
698 NULL, // current directory (use the same)
699 &si, // startup info (unused here)
700 &pi // process info
701 ) != 0;
702
703 #if wxUSE_STREAMS && !defined(__WXWINCE__)
704 // we can close the pipe ends used by child anyhow
705 if ( redirect )
706 {
707 ::CloseHandle(pipeIn.Detach(wxPipe::Read));
708 ::CloseHandle(pipeOut.Detach(wxPipe::Write));
709 ::CloseHandle(pipeErr.Detach(wxPipe::Write));
710 }
711 #endif // wxUSE_STREAMS
712
713 if ( !ok )
714 {
715 #if wxUSE_STREAMS && !defined(__WXWINCE__)
716 // close the other handles too
717 if ( redirect )
718 {
719 ::CloseHandle(pipeOut.Detach(wxPipe::Read));
720 ::CloseHandle(pipeErr.Detach(wxPipe::Read));
721 }
722 #endif // wxUSE_STREAMS
723
724 wxLogSysError(_("Execution of command '%s' failed"), command.c_str());
725
726 return flags & wxEXEC_SYNC ? -1 : 0;
727 }
728
729 #if wxUSE_STREAMS && !defined(__WXWINCE__)
730 // the input buffer bufOut is connected to stdout, this is why it is
731 // called bufOut and not bufIn
732 wxStreamTempInputBuffer bufOut,
733 bufErr;
734
735 if ( redirect )
736 {
737 // We can now initialize the wxStreams
738 wxPipeInputStream *
739 outStream = new wxPipeInputStream(pipeOut.Detach(wxPipe::Read));
740 wxPipeInputStream *
741 errStream = new wxPipeInputStream(pipeErr.Detach(wxPipe::Read));
742 wxPipeOutputStream *
743 inStream = new wxPipeOutputStream(hpipeStdinWrite);
744
745 handler->SetPipeStreams(outStream, inStream, errStream);
746
747 bufOut.Init(outStream);
748 bufErr.Init(errStream);
749 }
750 #endif // wxUSE_STREAMS
751
752 // create a hidden window to receive notification about process
753 // termination
754 HWND hwnd = wxCreateHiddenWindow
755 (
756 &gs_classForHiddenWindow,
757 wxMSWEXEC_WNDCLASSNAME,
758 (WNDPROC)wxExecuteWindowCbk
759 );
760
761 wxASSERT_MSG( hwnd, wxT("can't create a hidden window for wxExecute") );
762
763 // Alloc data
764 wxExecuteData *data = new wxExecuteData;
765 data->hProcess = pi.hProcess;
766 data->dwProcessId = pi.dwProcessId;
767 data->hWnd = hwnd;
768 data->state = (flags & wxEXEC_SYNC) != 0;
769 if ( flags & wxEXEC_SYNC )
770 {
771 // handler may be !NULL for capturing program output, but we don't use
772 // it wxExecuteData struct in this case
773 data->handler = NULL;
774 }
775 else
776 {
777 // may be NULL or not
778 data->handler = handler;
779 }
780
781 DWORD tid;
782 HANDLE hThread = ::CreateThread(NULL,
783 0,
784 wxExecuteThread,
785 (void *)data,
786 0,
787 &tid);
788
789 // resume process we created now - whether the thread creation succeeded or
790 // not
791 if ( ::ResumeThread(pi.hThread) == (DWORD)-1 )
792 {
793 // ignore it - what can we do?
794 wxLogLastError(wxT("ResumeThread in wxExecute"));
795 }
796
797 // close unneeded handle
798 if ( !::CloseHandle(pi.hThread) )
799 wxLogLastError(wxT("CloseHandle(hThread)"));
800
801 if ( !hThread )
802 {
803 wxLogLastError(wxT("CreateThread in wxExecute"));
804
805 DestroyWindow(hwnd);
806 delete data;
807
808 // the process still started up successfully...
809 return pi.dwProcessId;
810 }
811
812 ::CloseHandle(hThread);
813
814 #if wxUSE_IPC && !defined(__WXWINCE__)
815 // second part of DDE hack: now establish the DDE conversation with the
816 // just launched process
817 if ( !ddeServer.empty() )
818 {
819 bool ok;
820
821 // give the process the time to init itself
822 //
823 // we use a very big timeout hoping that WaitForInputIdle() will return
824 // much sooner, but not INFINITE just in case the process hangs
825 // completely - like this we will regain control sooner or later
826 switch ( ::WaitForInputIdle(pi.hProcess, 10000 /* 10 seconds */) )
827 {
828 default:
829 wxFAIL_MSG( _T("unexpected WaitForInputIdle() return code") );
830 // fall through
831
832 case -1:
833 wxLogLastError(_T("WaitForInputIdle() in wxExecute"));
834
835 case WAIT_TIMEOUT:
836 wxLogDebug(_T("Timeout too small in WaitForInputIdle"));
837
838 ok = FALSE;
839 break;
840
841 case 0:
842 // ok, process ready to accept DDE requests
843 ok = wxExecuteDDE(ddeServer, ddeTopic, ddeCommand);
844 }
845
846 if ( !ok )
847 {
848 wxLogDebug(_T("Failed to send DDE request to the process \"%s\"."),
849 cmd.c_str());
850 }
851 }
852 #endif // wxUSE_IPC
853
854 if ( !(flags & wxEXEC_SYNC) )
855 {
856 // clean up will be done when the process terminates
857
858 // return the pid
859 return pi.dwProcessId;
860 }
861
862 wxAppTraits *traits = wxTheApp ? wxTheApp->GetTraits() : NULL;
863 wxCHECK_MSG( traits, -1, _T("no wxAppTraits in wxExecute()?") );
864
865 // disable all app windows while waiting for the child process to finish
866 void *cookie = traits->BeforeChildWaitLoop();
867
868 // wait until the child process terminates
869 while ( data->state )
870 {
871 #if wxUSE_STREAMS && !defined(__WXWINCE__)
872 bufOut.Update();
873 bufErr.Update();
874 #endif // wxUSE_STREAMS
875
876 // don't eat 100% of the CPU -- ugly but anything else requires
877 // real async IO which we don't have for the moment
878 ::Sleep(50);
879
880 // we must process messages or we'd never get wxWM_PROC_TERMINATED
881 traits->AlwaysYield();
882 }
883
884 traits->AfterChildWaitLoop(cookie);
885
886 DWORD dwExitCode = data->dwExitCode;
887 delete data;
888
889 // return the exit code
890 return dwExitCode;
891 }
892
893 long wxExecute(wxChar **argv, int flags, wxProcess *handler)
894 {
895 wxString command;
896
897 for ( ;; )
898 {
899 command += *argv++;
900 if ( !*argv )
901 break;
902
903 command += _T(' ');
904 }
905
906 return wxExecute(command, flags, handler);
907 }
908