]> git.saurik.com Git - wxWidgets.git/blob - src/msw/utilsexc.cpp
always dispatch messages for the hidden window which receives process termination...
[wxWidgets.git] / src / msw / utilsexc.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/utilsexc.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 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
22
23 #ifdef __BORLANDC__
24 #pragma hdrstop
25 #endif
26
27 #ifndef WX_PRECOMP
28 #include "wx/utils.h"
29 #include "wx/app.h"
30 #include "wx/intl.h"
31 #include "wx/log.h"
32 #if wxUSE_STREAMS
33 #include "wx/stream.h"
34 #endif
35 #include "wx/module.h"
36 #endif
37
38 #include "wx/process.h"
39 #include "wx/thread.h"
40 #include "wx/apptrait.h"
41 #include "wx/evtloop.h"
42 #include "wx/vector.h"
43
44
45 #include "wx/msw/private.h"
46
47 #include <ctype.h>
48
49 #if !defined(__GNUWIN32__) && !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 // event used to wake up threads waiting in wxExecuteThread
107 static HANDLE gs_heventShutdown = NULL;
108
109 // handles of all threads monitoring the execution of asynchronously running
110 // processes
111 static wxVector<HANDLE> gs_asyncThreads;
112
113 // ----------------------------------------------------------------------------
114 // private types
115 // ----------------------------------------------------------------------------
116
117 // structure describing the process we're being waiting for
118 struct wxExecuteData
119 {
120 public:
121 ~wxExecuteData()
122 {
123 if ( !::CloseHandle(hProcess) )
124 {
125 wxLogLastError(wxT("CloseHandle(hProcess)"));
126 }
127 }
128
129 HWND hWnd; // window to send wxWM_PROC_TERMINATED to
130 HANDLE hProcess; // handle of the process
131 DWORD dwProcessId; // pid of the process
132 wxProcess *handler;
133 DWORD dwExitCode; // the exit code of the process
134 bool state; // set to false when the process finishes
135 };
136
137 class wxExecuteModule : public wxModule
138 {
139 public:
140 virtual bool OnInit() { return true; }
141 virtual void OnExit()
142 {
143 if ( gs_heventShutdown )
144 {
145 // stop any threads waiting for the termination of asynchronously
146 // running processes
147 if ( !::SetEvent(gs_heventShutdown) )
148 {
149 wxLogDebug(_T("Failed to set shutdown event in wxExecuteModule"));
150 }
151
152 ::CloseHandle(gs_heventShutdown);
153 gs_heventShutdown = NULL;
154
155 // now wait until they terminate
156 if ( !gs_asyncThreads.empty() )
157 {
158 const size_t numThreads = gs_asyncThreads.size();
159
160 if ( ::WaitForMultipleObjects
161 (
162 numThreads,
163 &gs_asyncThreads[0],
164 TRUE, // wait for all of them to become signalled
165 3000 // long but finite value
166 ) == WAIT_TIMEOUT )
167 {
168 wxLogDebug(_T("Failed to stop all wxExecute monitor threads"));
169 }
170
171 for ( size_t n = 0; n < numThreads; n++ )
172 {
173 ::CloseHandle(gs_asyncThreads[n]);
174 }
175
176 gs_asyncThreads.clear();
177 }
178 }
179
180 if ( gs_classForHiddenWindow )
181 {
182 if ( !::UnregisterClass(wxMSWEXEC_WNDCLASSNAME, wxGetInstance()) )
183 {
184 wxLogLastError(_T("UnregisterClass(wxExecClass)"));
185 }
186
187 gs_classForHiddenWindow = NULL;
188 }
189 }
190
191 private:
192 DECLARE_DYNAMIC_CLASS(wxExecuteModule)
193 };
194
195 IMPLEMENT_DYNAMIC_CLASS(wxExecuteModule, wxModule)
196
197 #if wxUSE_STREAMS && !defined(__WXWINCE__)
198
199 // ----------------------------------------------------------------------------
200 // wxPipeStreams
201 // ----------------------------------------------------------------------------
202
203 class wxPipeInputStream: public wxInputStream
204 {
205 public:
206 wxPipeInputStream(HANDLE hInput);
207 virtual ~wxPipeInputStream();
208
209 // returns true if the pipe is still opened
210 bool IsOpened() const { return m_hInput != INVALID_HANDLE_VALUE; }
211
212 // returns true if there is any data to be read from the pipe
213 virtual bool CanRead() const;
214
215 protected:
216 size_t OnSysRead(void *buffer, size_t len);
217
218 protected:
219 HANDLE m_hInput;
220
221 wxDECLARE_NO_COPY_CLASS(wxPipeInputStream);
222 };
223
224 class wxPipeOutputStream: public wxOutputStream
225 {
226 public:
227 wxPipeOutputStream(HANDLE hOutput);
228 virtual ~wxPipeOutputStream() { Close(); }
229 bool Close();
230
231 protected:
232 size_t OnSysWrite(const void *buffer, size_t len);
233
234 protected:
235 HANDLE m_hOutput;
236
237 wxDECLARE_NO_COPY_CLASS(wxPipeOutputStream);
238 };
239
240 // define this to let wxexec.cpp know that we know what we're doing
241 #define _WX_USED_BY_WXEXECUTE_
242 #include "../common/execcmn.cpp"
243
244 // ----------------------------------------------------------------------------
245 // wxPipe represents a Win32 anonymous pipe
246 // ----------------------------------------------------------------------------
247
248 class wxPipe
249 {
250 public:
251 // the symbolic names for the pipe ends
252 enum Direction
253 {
254 Read,
255 Write
256 };
257
258 // default ctor doesn't do anything
259 wxPipe() { m_handles[Read] = m_handles[Write] = INVALID_HANDLE_VALUE; }
260
261 // create the pipe, return true if ok, false on error
262 bool Create()
263 {
264 // default secutiry attributes
265 SECURITY_ATTRIBUTES security;
266
267 security.nLength = sizeof(security);
268 security.lpSecurityDescriptor = NULL;
269 security.bInheritHandle = TRUE; // to pass it to the child
270
271 if ( !::CreatePipe(&m_handles[0], &m_handles[1], &security, 0) )
272 {
273 wxLogSysError(_("Failed to create an anonymous pipe"));
274
275 return false;
276 }
277
278 return true;
279 }
280
281 // return true if we were created successfully
282 bool IsOk() const { return m_handles[Read] != INVALID_HANDLE_VALUE; }
283
284 // return the descriptor for one of the pipe ends
285 HANDLE operator[](Direction which) const { return m_handles[which]; }
286
287 // detach a descriptor, meaning that the pipe dtor won't close it, and
288 // return it
289 HANDLE Detach(Direction which)
290 {
291 HANDLE handle = m_handles[which];
292 m_handles[which] = INVALID_HANDLE_VALUE;
293
294 return handle;
295 }
296
297 // close the pipe descriptors
298 void Close()
299 {
300 for ( size_t n = 0; n < WXSIZEOF(m_handles); n++ )
301 {
302 if ( m_handles[n] != INVALID_HANDLE_VALUE )
303 {
304 ::CloseHandle(m_handles[n]);
305 m_handles[n] = INVALID_HANDLE_VALUE;
306 }
307 }
308 }
309
310 // dtor closes the pipe descriptors
311 ~wxPipe() { Close(); }
312
313 private:
314 HANDLE m_handles[2];
315 };
316
317 #endif // wxUSE_STREAMS
318
319 // ============================================================================
320 // implementation
321 // ============================================================================
322
323 // ----------------------------------------------------------------------------
324 // process termination detecting support
325 // ----------------------------------------------------------------------------
326
327 // thread function for the thread monitoring the process termination
328 static DWORD __stdcall wxExecuteThread(void *arg)
329 {
330 wxExecuteData * const data = (wxExecuteData *)arg;
331
332 // create the shutdown event if we're the first thread starting to wait
333 if ( !gs_heventShutdown )
334 {
335 // create a manual initially non-signalled event object
336 gs_heventShutdown = ::CreateEvent(NULL, TRUE, FALSE, NULL);
337 if ( !gs_heventShutdown )
338 {
339 wxLogDebug(_T("CreateEvent() in wxExecuteThread failed"));
340 }
341 }
342
343 HANDLE handles[2] = { data->hProcess, gs_heventShutdown };
344 switch ( ::WaitForMultipleObjects(2, handles, FALSE, INFINITE) )
345 {
346 case WAIT_OBJECT_0:
347 // process terminated, get its exit code
348 if ( !::GetExitCodeProcess(data->hProcess, &data->dwExitCode) )
349 {
350 wxLogLastError(wxT("GetExitCodeProcess"));
351 }
352
353 wxASSERT_MSG( data->dwExitCode != STILL_ACTIVE,
354 wxT("process should have terminated") );
355
356 // send a message indicating process termination to the window
357 ::SendMessage(data->hWnd, wxWM_PROC_TERMINATED, 0, (LPARAM)data);
358 break;
359
360 case WAIT_OBJECT_0 + 1:
361 // we're shutting down but the process is still running -- leave it
362 // run but clean up the associated data
363 if ( !data->state )
364 {
365 delete data;
366 }
367 //else: exiting while synchronously executing process is still
368 // running? this shouldn't happen...
369 break;
370
371 default:
372 wxLogDebug(_T("Waiting for the process termination failed!"));
373 }
374
375 return 0;
376 }
377
378 // window procedure of a hidden window which is created just to receive
379 // the notification message when a process exits
380 LRESULT APIENTRY _EXPORT wxExecuteWindowCbk(HWND hWnd, UINT message,
381 WPARAM wParam, LPARAM lParam)
382 {
383 if ( message == wxWM_PROC_TERMINATED )
384 {
385 DestroyWindow(hWnd); // we don't need it any more
386
387 wxExecuteData * const data = (wxExecuteData *)lParam;
388 if ( data->handler )
389 {
390 data->handler->OnTerminate((int)data->dwProcessId,
391 (int)data->dwExitCode);
392 }
393
394 if ( data->state )
395 {
396 // we're executing synchronously, tell the waiting thread
397 // that the process finished
398 data->state = false;
399 }
400 else
401 {
402 // asynchronous execution - we should do the clean up
403 delete data;
404 }
405
406 return 0;
407 }
408 else
409 {
410 return ::DefWindowProc(hWnd, message, wParam, lParam);
411 }
412 }
413
414 // ============================================================================
415 // implementation of IO redirection support classes
416 // ============================================================================
417
418 #if wxUSE_STREAMS && !defined(__WXWINCE__)
419
420 // ----------------------------------------------------------------------------
421 // wxPipeInputStreams
422 // ----------------------------------------------------------------------------
423
424 wxPipeInputStream::wxPipeInputStream(HANDLE hInput)
425 {
426 m_hInput = hInput;
427 }
428
429 wxPipeInputStream::~wxPipeInputStream()
430 {
431 if ( m_hInput != INVALID_HANDLE_VALUE )
432 ::CloseHandle(m_hInput);
433 }
434
435 bool wxPipeInputStream::CanRead() const
436 {
437 // we can read if there's something in the put back buffer
438 // even pipe is closed
439 if ( m_wbacksize > m_wbackcur )
440 return true;
441
442 wxPipeInputStream * const self = wxConstCast(this, wxPipeInputStream);
443
444 if ( !IsOpened() )
445 {
446 // set back to mark Eof as it may have been unset by Ungetch()
447 self->m_lasterror = wxSTREAM_EOF;
448 return false;
449 }
450
451 DWORD nAvailable;
452
453 // function name is misleading, it works with anon pipes as well
454 DWORD rc = ::PeekNamedPipe
455 (
456 m_hInput, // handle
457 NULL, 0, // ptr to buffer and its size
458 NULL, // [out] bytes read
459 &nAvailable, // [out] bytes available
460 NULL // [out] bytes left
461 );
462
463 if ( !rc )
464 {
465 if ( ::GetLastError() != ERROR_BROKEN_PIPE )
466 {
467 // unexpected error
468 wxLogLastError(_T("PeekNamedPipe"));
469 }
470
471 // don't try to continue reading from a pipe if an error occurred or if
472 // it had been closed
473 ::CloseHandle(m_hInput);
474
475 self->m_hInput = INVALID_HANDLE_VALUE;
476 self->m_lasterror = wxSTREAM_EOF;
477
478 nAvailable = 0;
479 }
480
481 return nAvailable != 0;
482 }
483
484 size_t wxPipeInputStream::OnSysRead(void *buffer, size_t len)
485 {
486 if ( !IsOpened() )
487 {
488 m_lasterror = wxSTREAM_EOF;
489
490 return 0;
491 }
492
493 DWORD bytesRead;
494 if ( !::ReadFile(m_hInput, buffer, len, &bytesRead, NULL) )
495 {
496 m_lasterror = ::GetLastError() == ERROR_BROKEN_PIPE
497 ? wxSTREAM_EOF
498 : wxSTREAM_READ_ERROR;
499 }
500
501 // bytesRead is set to 0, as desired, if an error occurred
502 return bytesRead;
503 }
504
505 // ----------------------------------------------------------------------------
506 // wxPipeOutputStream
507 // ----------------------------------------------------------------------------
508
509 wxPipeOutputStream::wxPipeOutputStream(HANDLE hOutput)
510 {
511 m_hOutput = hOutput;
512
513 // unblock the pipe to prevent deadlocks when we're writing to the pipe
514 // from which the child process can't read because it is writing in its own
515 // end of it
516 DWORD mode = PIPE_READMODE_BYTE | PIPE_NOWAIT;
517 if ( !::SetNamedPipeHandleState
518 (
519 m_hOutput,
520 &mode,
521 NULL, // collection count (we don't set it)
522 NULL // timeout (we don't set it neither)
523 ) )
524 {
525 wxLogLastError(_T("SetNamedPipeHandleState(PIPE_NOWAIT)"));
526 }
527 }
528
529 bool wxPipeOutputStream::Close()
530 {
531 return ::CloseHandle(m_hOutput) != 0;
532 }
533
534
535 size_t wxPipeOutputStream::OnSysWrite(const void *buffer, size_t len)
536 {
537 m_lasterror = wxSTREAM_NO_ERROR;
538
539 DWORD totalWritten = 0;
540 while ( len > 0 )
541 {
542 DWORD chunkWritten;
543 if ( !::WriteFile(m_hOutput, buffer, len, &chunkWritten, NULL) )
544 {
545 m_lasterror = ::GetLastError() == ERROR_BROKEN_PIPE
546 ? wxSTREAM_EOF
547 : wxSTREAM_WRITE_ERROR;
548 break;
549 }
550
551 if ( !chunkWritten )
552 break;
553
554 buffer = (char *)buffer + chunkWritten;
555 totalWritten += chunkWritten;
556 len -= chunkWritten;
557 }
558
559 return totalWritten;
560 }
561
562 #endif // wxUSE_STREAMS
563
564 // ============================================================================
565 // wxExecute functions family
566 // ============================================================================
567
568 #if wxUSE_IPC
569
570 // connect to the given server via DDE and ask it to execute the command
571 bool
572 wxExecuteDDE(const wxString& ddeServer,
573 const wxString& ddeTopic,
574 const wxString& ddeCommand)
575 {
576 bool ok wxDUMMY_INITIALIZE(false);
577
578 wxDDEClient client;
579 wxConnectionBase *
580 conn = client.MakeConnection(wxEmptyString, ddeServer, ddeTopic);
581 if ( !conn )
582 {
583 ok = false;
584 }
585 else // connected to DDE server
586 {
587 // the added complication here is that although most programs use
588 // XTYP_EXECUTE for their DDE API, some important ones -- like Word
589 // and other MS stuff - use XTYP_REQUEST!
590 //
591 // moreover, anotheri mportant program (IE) understands both but
592 // returns an error from Execute() so we must try Request() first
593 // to avoid doing it twice
594 {
595 // we're prepared for this one to fail, so don't show errors
596 wxLogNull noErrors;
597
598 ok = conn->Request(ddeCommand) != NULL;
599 }
600
601 if ( !ok )
602 {
603 // now try execute -- but show the errors
604 ok = conn->Execute(ddeCommand);
605 }
606 }
607
608 return ok;
609 }
610
611 #endif // wxUSE_IPC
612
613 long wxExecute(const wxString& cmd, int flags, wxProcess *handler)
614 {
615 wxCHECK_MSG( !cmd.empty(), 0, wxT("empty command in wxExecute") );
616
617 #if wxUSE_THREADS
618 // for many reasons, the code below breaks down if it's called from another
619 // thread -- this could be fixed, but as Unix versions don't support this
620 // neither I don't want to waste time on this now
621 wxASSERT_MSG( wxThread::IsMain(),
622 _T("wxExecute() can be called only from the main thread") );
623 #endif // wxUSE_THREADS
624
625 wxString command;
626
627 #if wxUSE_IPC
628 // DDE hack: this is really not pretty, but we need to allow this for
629 // transparent handling of DDE servers in wxMimeTypesManager. Usually it
630 // returns the command which should be run to view/open/... a file of the
631 // given type. Sometimes, however, this command just launches the server
632 // and an additional DDE request must be made to really open the file. To
633 // keep all this well hidden from the application, we allow a special form
634 // of command: WX_DDE#<command>#DDE_SERVER#DDE_TOPIC#DDE_COMMAND in which
635 // case we execute just <command> and process the rest below
636 wxString ddeServer, ddeTopic, ddeCommand;
637 static const size_t lenDdePrefix = 7; // strlen("WX_DDE:")
638 if ( cmd.Left(lenDdePrefix) == _T("WX_DDE#") )
639 {
640 // speed up the concatenations below
641 ddeServer.reserve(256);
642 ddeTopic.reserve(256);
643 ddeCommand.reserve(256);
644
645 const wxChar *p = cmd.c_str() + 7;
646 while ( *p && *p != _T('#') )
647 {
648 command += *p++;
649 }
650
651 if ( *p )
652 {
653 // skip '#'
654 p++;
655 }
656 else
657 {
658 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
659 }
660
661 while ( *p && *p != _T('#') )
662 {
663 ddeServer += *p++;
664 }
665
666 if ( *p )
667 {
668 // skip '#'
669 p++;
670 }
671 else
672 {
673 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
674 }
675
676 while ( *p && *p != _T('#') )
677 {
678 ddeTopic += *p++;
679 }
680
681 if ( *p )
682 {
683 // skip '#'
684 p++;
685 }
686 else
687 {
688 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
689 }
690
691 while ( *p )
692 {
693 ddeCommand += *p++;
694 }
695
696 // if we want to just launch the program and not wait for its
697 // termination, try to execute DDE command right now, it can succeed if
698 // the process is already running - but as it fails if it's not
699 // running, suppress any errors it might generate
700 if ( !(flags & wxEXEC_SYNC) )
701 {
702 wxLogNull noErrors;
703 if ( wxExecuteDDE(ddeServer, ddeTopic, ddeCommand) )
704 {
705 // a dummy PID - this is a hack, of course, but it's well worth
706 // it as we don't open a new server each time we're called
707 // which would be quite bad
708 return -1;
709 }
710 }
711 }
712 else
713 #endif // wxUSE_IPC
714 {
715 // no DDE
716 command = cmd;
717 }
718
719 // the IO redirection is only supported with wxUSE_STREAMS
720 BOOL redirect = FALSE;
721
722 #if wxUSE_STREAMS && !defined(__WXWINCE__)
723 wxPipe pipeIn, pipeOut, pipeErr;
724
725 // we'll save here the copy of pipeIn[Write]
726 HANDLE hpipeStdinWrite = INVALID_HANDLE_VALUE;
727
728 // open the pipes to which child process IO will be redirected if needed
729 if ( handler && handler->IsRedirected() )
730 {
731 // create pipes for redirecting stdin, stdout and stderr
732 if ( !pipeIn.Create() || !pipeOut.Create() || !pipeErr.Create() )
733 {
734 wxLogSysError(_("Failed to redirect the child process IO"));
735
736 // indicate failure: we need to return different error code
737 // depending on the sync flag
738 return flags & wxEXEC_SYNC ? -1 : 0;
739 }
740
741 redirect = TRUE;
742 }
743 #endif // wxUSE_STREAMS
744
745 // create the process
746 STARTUPINFO si;
747 wxZeroMemory(si);
748 si.cb = sizeof(si);
749
750 #if wxUSE_STREAMS && !defined(__WXWINCE__)
751 if ( redirect )
752 {
753 si.dwFlags = STARTF_USESTDHANDLES;
754
755 si.hStdInput = pipeIn[wxPipe::Read];
756 si.hStdOutput = pipeOut[wxPipe::Write];
757 si.hStdError = pipeErr[wxPipe::Write];
758
759 // when the std IO is redirected, we don't show the (console) process
760 // window by default, but this can be overridden by the caller by
761 // specifying wxEXEC_NOHIDE flag
762 if ( !(flags & wxEXEC_NOHIDE) )
763 {
764 si.dwFlags |= STARTF_USESHOWWINDOW;
765 si.wShowWindow = SW_HIDE;
766 }
767
768 // we must duplicate the handle to the write side of stdin pipe to make
769 // it non inheritable: indeed, we must close the writing end of pipeIn
770 // before launching the child process as otherwise this handle will be
771 // inherited by the child which will never close it and so the pipe
772 // will never be closed and the child will be left stuck in ReadFile()
773 HANDLE pipeInWrite = pipeIn.Detach(wxPipe::Write);
774 if ( !::DuplicateHandle
775 (
776 ::GetCurrentProcess(),
777 pipeInWrite,
778 ::GetCurrentProcess(),
779 &hpipeStdinWrite,
780 0, // desired access: unused here
781 FALSE, // not inherited
782 DUPLICATE_SAME_ACCESS // same access as for src handle
783 ) )
784 {
785 wxLogLastError(_T("DuplicateHandle"));
786 }
787
788 ::CloseHandle(pipeInWrite);
789 }
790 #endif // wxUSE_STREAMS
791
792 PROCESS_INFORMATION pi;
793 DWORD dwFlags = CREATE_SUSPENDED;
794
795 #ifndef __WXWINCE__
796 dwFlags |= CREATE_DEFAULT_ERROR_MODE ;
797 #else
798 // we are assuming commands without spaces for now
799 wxString moduleName = command.BeforeFirst(wxT(' '));
800 wxString arguments = command.AfterFirst(wxT(' '));
801 #endif
802
803 bool ok = ::CreateProcess
804 (
805 // WinCE requires appname to be non null
806 // Win32 allows for null
807 #ifdef __WXWINCE__
808 (wxChar *)
809 moduleName.wx_str(),// application name
810 (wxChar *)
811 arguments.wx_str(), // arguments
812 #else
813 NULL, // application name (use only cmd line)
814 (wxChar *)
815 command.wx_str(), // full command line
816 #endif
817 NULL, // security attributes: defaults for both
818 NULL, // the process and its main thread
819 redirect, // inherit handles if we use pipes
820 dwFlags, // process creation flags
821 NULL, // environment (use the same)
822 NULL, // current directory (use the same)
823 &si, // startup info (unused here)
824 &pi // process info
825 ) != 0;
826
827 #if wxUSE_STREAMS && !defined(__WXWINCE__)
828 // we can close the pipe ends used by child anyhow
829 if ( redirect )
830 {
831 ::CloseHandle(pipeIn.Detach(wxPipe::Read));
832 ::CloseHandle(pipeOut.Detach(wxPipe::Write));
833 ::CloseHandle(pipeErr.Detach(wxPipe::Write));
834 }
835 #endif // wxUSE_STREAMS
836
837 if ( !ok )
838 {
839 #if wxUSE_STREAMS && !defined(__WXWINCE__)
840 // close the other handles too
841 if ( redirect )
842 {
843 ::CloseHandle(pipeOut.Detach(wxPipe::Read));
844 ::CloseHandle(pipeErr.Detach(wxPipe::Read));
845 }
846 #endif // wxUSE_STREAMS
847
848 wxLogSysError(_("Execution of command '%s' failed"), command.c_str());
849
850 return flags & wxEXEC_SYNC ? -1 : 0;
851 }
852
853 #if wxUSE_STREAMS && !defined(__WXWINCE__)
854 // the input buffer bufOut is connected to stdout, this is why it is
855 // called bufOut and not bufIn
856 wxStreamTempInputBuffer bufOut,
857 bufErr;
858
859 if ( redirect )
860 {
861 // We can now initialize the wxStreams
862 wxPipeInputStream *
863 outStream = new wxPipeInputStream(pipeOut.Detach(wxPipe::Read));
864 wxPipeInputStream *
865 errStream = new wxPipeInputStream(pipeErr.Detach(wxPipe::Read));
866 wxPipeOutputStream *
867 inStream = new wxPipeOutputStream(hpipeStdinWrite);
868
869 handler->SetPipeStreams(outStream, inStream, errStream);
870
871 bufOut.Init(outStream);
872 bufErr.Init(errStream);
873 }
874 #endif // wxUSE_STREAMS
875
876 // create a hidden window to receive notification about process
877 // termination
878 HWND hwnd = wxCreateHiddenWindow
879 (
880 &gs_classForHiddenWindow,
881 wxMSWEXEC_WNDCLASSNAME,
882 (WNDPROC)wxExecuteWindowCbk
883 );
884
885 wxASSERT_MSG( hwnd, wxT("can't create a hidden window for wxExecute") );
886
887 // Alloc data
888 wxExecuteData *data = new wxExecuteData;
889 data->hProcess = pi.hProcess;
890 data->dwProcessId = pi.dwProcessId;
891 data->hWnd = hwnd;
892 data->state = (flags & wxEXEC_SYNC) != 0;
893 if ( flags & wxEXEC_SYNC )
894 {
895 // handler may be !NULL for capturing program output, but we don't use
896 // it wxExecuteData struct in this case
897 data->handler = NULL;
898 }
899 else
900 {
901 // may be NULL or not
902 data->handler = handler;
903
904 if (handler)
905 handler->SetPid(pi.dwProcessId);
906 }
907
908 DWORD tid;
909 HANDLE hThread = ::CreateThread(NULL,
910 0,
911 wxExecuteThread,
912 (void *)data,
913 0,
914 &tid);
915
916 // resume process we created now - whether the thread creation succeeded or
917 // not
918 if ( ::ResumeThread(pi.hThread) == (DWORD)-1 )
919 {
920 // ignore it - what can we do?
921 wxLogLastError(wxT("ResumeThread in wxExecute"));
922 }
923
924 // close unneeded handle
925 if ( !::CloseHandle(pi.hThread) )
926 wxLogLastError(wxT("CloseHandle(hThread)"));
927
928 if ( !hThread )
929 {
930 wxLogLastError(wxT("CreateThread in wxExecute"));
931
932 DestroyWindow(hwnd);
933 delete data;
934
935 // the process still started up successfully...
936 return pi.dwProcessId;
937 }
938
939 gs_asyncThreads.push_back(hThread);
940
941 #if wxUSE_IPC && !defined(__WXWINCE__)
942 // second part of DDE hack: now establish the DDE conversation with the
943 // just launched process
944 if ( !ddeServer.empty() )
945 {
946 bool ok;
947
948 // give the process the time to init itself
949 //
950 // we use a very big timeout hoping that WaitForInputIdle() will return
951 // much sooner, but not INFINITE just in case the process hangs
952 // completely - like this we will regain control sooner or later
953 switch ( ::WaitForInputIdle(pi.hProcess, 10000 /* 10 seconds */) )
954 {
955 default:
956 wxFAIL_MSG( _T("unexpected WaitForInputIdle() return code") );
957 // fall through
958
959 case -1:
960 wxLogLastError(_T("WaitForInputIdle() in wxExecute"));
961
962 case WAIT_TIMEOUT:
963 wxLogDebug(_T("Timeout too small in WaitForInputIdle"));
964
965 ok = false;
966 break;
967
968 case 0:
969 // ok, process ready to accept DDE requests
970 ok = wxExecuteDDE(ddeServer, ddeTopic, ddeCommand);
971 }
972
973 if ( !ok )
974 {
975 wxLogDebug(_T("Failed to send DDE request to the process \"%s\"."),
976 cmd.c_str());
977 }
978 }
979 #endif // wxUSE_IPC
980
981 if ( !(flags & wxEXEC_SYNC) )
982 {
983 // clean up will be done when the process terminates
984
985 // return the pid
986 return pi.dwProcessId;
987 }
988
989 wxAppTraits *traits = wxTheApp ? wxTheApp->GetTraits() : NULL;
990 wxCHECK_MSG( traits, -1, _T("no wxAppTraits in wxExecute()?") );
991
992 void *cookie = NULL;
993 if ( !(flags & wxEXEC_NODISABLE) )
994 {
995 // disable all app windows while waiting for the child process to finish
996 cookie = traits->BeforeChildWaitLoop();
997 }
998
999 // wait until the child process terminates
1000 while ( data->state )
1001 {
1002 #if wxUSE_STREAMS && !defined(__WXWINCE__)
1003 if ( !bufOut.Update() && !bufErr.Update() )
1004 #endif // wxUSE_STREAMS
1005 {
1006 // don't eat 100% of the CPU -- ugly but anything else requires
1007 // real async IO which we don't have for the moment
1008 ::Sleep(50);
1009 }
1010
1011 // we must always process messages for our hidden window or we'd never
1012 // get wxWM_PROC_TERMINATED and so this loop would never terminate
1013 MSG msg;
1014 ::PeekMessage(&msg, data->hWnd, 0, 0, PM_REMOVE);
1015
1016 // we may also need to process messages for all the other application
1017 // windows
1018 if ( !(flags & wxEXEC_NOEVENTS) )
1019 {
1020 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
1021 if ( loop )
1022 loop->Yield();
1023 }
1024 }
1025
1026 if ( !(flags & wxEXEC_NODISABLE) )
1027 {
1028 // reenable disabled windows back
1029 traits->AfterChildWaitLoop(cookie);
1030 }
1031
1032 DWORD dwExitCode = data->dwExitCode;
1033 delete data;
1034
1035 // return the exit code
1036 return dwExitCode;
1037 }
1038
1039 template <typename CharType>
1040 long wxExecuteImpl(CharType **argv, int flags, wxProcess *handler)
1041 {
1042 wxString command;
1043 command.reserve(1024);
1044
1045 wxString arg;
1046 for ( ;; )
1047 {
1048 arg = *argv++;
1049
1050 bool quote;
1051 if ( arg.empty() )
1052 {
1053 // we need to quote empty arguments, otherwise they'd just
1054 // disappear
1055 quote = true;
1056 }
1057 else // non-empty
1058 {
1059 // escape any quotes present in the string to avoid interfering
1060 // with the command line parsing in the child process
1061 arg.Replace("\"", "\\\"", true /* replace all */);
1062
1063 // and quote any arguments containing the spaces to prevent them from
1064 // being broken down
1065 quote = arg.find_first_of(" \t") != wxString::npos;
1066 }
1067
1068 if ( quote )
1069 command += '\"' + arg + '\"';
1070 else
1071 command += arg;
1072
1073 if ( !*argv )
1074 break;
1075
1076 command += ' ';
1077 }
1078
1079 return wxExecute(command, flags, handler);
1080 }
1081
1082 long wxExecute(char **argv, int flags, wxProcess *handler)
1083 {
1084 return wxExecuteImpl(argv, flags, handler);
1085 }
1086
1087 #if wxUSE_UNICODE
1088
1089 long wxExecute(wchar_t **argv, int flags, wxProcess *handler)
1090 {
1091 return wxExecuteImpl(argv, flags, handler);
1092 }
1093
1094 #endif // wxUSE_UNICODE