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