1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/utilsexc.cpp
3 // Purpose: wxExecute implementation for MSW
4 // Author: Julian Smart
8 // Copyright: (c) 1998-2002 wxWidgets dev team
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
33 #include "wx/stream.h"
35 #include "wx/module.h"
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"
45 #include "wx/msw/private.h"
49 #if !defined(__GNUWIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
54 #if defined(__GNUWIN32__)
55 #include <sys/unistd.h>
59 #if !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
73 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
80 #include "wx/dde.h" // for WX_DDE hack in wxExecute
83 #include "wx/msw/private/hiddenwin.h"
85 // FIXME-VC6: These are not defined in VC6 SDK headers.
86 #ifndef BELOW_NORMAL_PRIORITY_CLASS
87 #define BELOW_NORMAL_PRIORITY_CLASS 0x4000
90 #ifndef ABOVE_NORMAL_PRIORITY_CLASS
91 #define ABOVE_NORMAL_PRIORITY_CLASS 0x8000
94 // ----------------------------------------------------------------------------
96 // ----------------------------------------------------------------------------
98 // this message is sent when the process we're waiting for terminates
99 #define wxWM_PROC_TERMINATED (WM_USER + 10000)
101 // ----------------------------------------------------------------------------
102 // this module globals
103 // ----------------------------------------------------------------------------
105 // we need to create a hidden window to receive the process termination
106 // notifications and for this we need a (Win) class name for it which we will
107 // register the first time it's needed
108 static const wxChar
*wxMSWEXEC_WNDCLASSNAME
= wxT("_wxExecute_Internal_Class");
109 static const wxChar
*gs_classForHiddenWindow
= NULL
;
111 // event used to wake up threads waiting in wxExecuteThread
112 static HANDLE gs_heventShutdown
= NULL
;
114 // handles of all threads monitoring the execution of asynchronously running
116 static wxVector
<HANDLE
> gs_asyncThreads
;
118 // ----------------------------------------------------------------------------
120 // ----------------------------------------------------------------------------
122 // structure describing the process we're being waiting for
128 if ( !::CloseHandle(hProcess
) )
130 wxLogLastError(wxT("CloseHandle(hProcess)"));
134 HWND hWnd
; // window to send wxWM_PROC_TERMINATED to
135 HANDLE hProcess
; // handle of the process
136 DWORD dwProcessId
; // pid of the process
138 DWORD dwExitCode
; // the exit code of the process
139 bool state
; // set to false when the process finishes
142 class wxExecuteModule
: public wxModule
145 virtual bool OnInit() { return true; }
146 virtual void OnExit()
148 if ( gs_heventShutdown
)
150 // stop any threads waiting for the termination of asynchronously
152 if ( !::SetEvent(gs_heventShutdown
) )
154 wxLogDebug(wxT("Failed to set shutdown event in wxExecuteModule"));
157 ::CloseHandle(gs_heventShutdown
);
158 gs_heventShutdown
= NULL
;
160 // now wait until they terminate
161 if ( !gs_asyncThreads
.empty() )
163 const size_t numThreads
= gs_asyncThreads
.size();
165 if ( ::WaitForMultipleObjects
169 TRUE
, // wait for all of them to become signalled
170 3000 // long but finite value
173 wxLogDebug(wxT("Failed to stop all wxExecute monitor threads"));
176 for ( size_t n
= 0; n
< numThreads
; n
++ )
178 ::CloseHandle(gs_asyncThreads
[n
]);
181 gs_asyncThreads
.clear();
185 if ( gs_classForHiddenWindow
)
187 if ( !::UnregisterClass(wxMSWEXEC_WNDCLASSNAME
, wxGetInstance()) )
189 wxLogLastError(wxT("UnregisterClass(wxExecClass)"));
192 gs_classForHiddenWindow
= NULL
;
197 DECLARE_DYNAMIC_CLASS(wxExecuteModule
)
200 IMPLEMENT_DYNAMIC_CLASS(wxExecuteModule
, wxModule
)
202 #if wxUSE_STREAMS && !defined(__WXWINCE__)
204 #include "wx/private/pipestream.h"
205 #include "wx/private/streamtempinput.h"
207 // ----------------------------------------------------------------------------
208 // wxPipe represents a Win32 anonymous pipe
209 // ----------------------------------------------------------------------------
214 // the symbolic names for the pipe ends
221 // default ctor doesn't do anything
222 wxPipe() { m_handles
[Read
] = m_handles
[Write
] = INVALID_HANDLE_VALUE
; }
224 // create the pipe, return true if ok, false on error
227 // default secutiry attributes
228 SECURITY_ATTRIBUTES security
;
230 security
.nLength
= sizeof(security
);
231 security
.lpSecurityDescriptor
= NULL
;
232 security
.bInheritHandle
= TRUE
; // to pass it to the child
234 if ( !::CreatePipe(&m_handles
[0], &m_handles
[1], &security
, 0) )
236 wxLogSysError(_("Failed to create an anonymous pipe"));
244 // return true if we were created successfully
245 bool IsOk() const { return m_handles
[Read
] != INVALID_HANDLE_VALUE
; }
247 // return the descriptor for one of the pipe ends
248 HANDLE
operator[](Direction which
) const { return m_handles
[which
]; }
250 // detach a descriptor, meaning that the pipe dtor won't close it, and
252 HANDLE
Detach(Direction which
)
254 HANDLE handle
= m_handles
[which
];
255 m_handles
[which
] = INVALID_HANDLE_VALUE
;
260 // close the pipe descriptors
263 for ( size_t n
= 0; n
< WXSIZEOF(m_handles
); n
++ )
265 if ( m_handles
[n
] != INVALID_HANDLE_VALUE
)
267 ::CloseHandle(m_handles
[n
]);
268 m_handles
[n
] = INVALID_HANDLE_VALUE
;
273 // dtor closes the pipe descriptors
274 ~wxPipe() { Close(); }
280 #endif // wxUSE_STREAMS
282 // ============================================================================
284 // ============================================================================
286 // ----------------------------------------------------------------------------
287 // process termination detecting support
288 // ----------------------------------------------------------------------------
290 // thread function for the thread monitoring the process termination
291 static DWORD __stdcall
wxExecuteThread(void *arg
)
293 wxExecuteData
* const data
= (wxExecuteData
*)arg
;
295 // create the shutdown event if we're the first thread starting to wait
296 if ( !gs_heventShutdown
)
298 // create a manual initially non-signalled event object
299 gs_heventShutdown
= ::CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
300 if ( !gs_heventShutdown
)
302 wxLogDebug(wxT("CreateEvent() in wxExecuteThread failed"));
306 HANDLE handles
[2] = { data
->hProcess
, gs_heventShutdown
};
307 switch ( ::WaitForMultipleObjects(2, handles
, FALSE
, INFINITE
) )
310 // process terminated, get its exit code
311 if ( !::GetExitCodeProcess(data
->hProcess
, &data
->dwExitCode
) )
313 wxLogLastError(wxT("GetExitCodeProcess"));
316 wxASSERT_MSG( data
->dwExitCode
!= STILL_ACTIVE
,
317 wxT("process should have terminated") );
319 // send a message indicating process termination to the window
320 ::SendMessage(data
->hWnd
, wxWM_PROC_TERMINATED
, 0, (LPARAM
)data
);
323 case WAIT_OBJECT_0
+ 1:
324 // we're shutting down but the process is still running -- leave it
325 // run but clean up the associated data
330 //else: exiting while synchronously executing process is still
331 // running? this shouldn't happen...
335 wxLogDebug(wxT("Waiting for the process termination failed!"));
341 // window procedure of a hidden window which is created just to receive
342 // the notification message when a process exits
343 LRESULT APIENTRY _EXPORT
wxExecuteWindowCbk(HWND hWnd
, UINT message
,
344 WPARAM wParam
, LPARAM lParam
)
346 if ( message
== wxWM_PROC_TERMINATED
)
348 DestroyWindow(hWnd
); // we don't need it any more
350 wxExecuteData
* const data
= (wxExecuteData
*)lParam
;
353 data
->handler
->OnTerminate((int)data
->dwProcessId
,
354 (int)data
->dwExitCode
);
359 // we're executing synchronously, tell the waiting thread
360 // that the process finished
365 // asynchronous execution - we should do the clean up
373 return ::DefWindowProc(hWnd
, message
, wParam
, lParam
);
377 // ============================================================================
378 // implementation of IO redirection support classes
379 // ============================================================================
381 #if wxUSE_STREAMS && !defined(__WXWINCE__)
383 // ----------------------------------------------------------------------------
384 // wxPipeInputStreams
385 // ----------------------------------------------------------------------------
387 wxPipeInputStream::wxPipeInputStream(HANDLE hInput
)
392 wxPipeInputStream::~wxPipeInputStream()
394 if ( m_hInput
!= INVALID_HANDLE_VALUE
)
395 ::CloseHandle(m_hInput
);
398 bool wxPipeInputStream::CanRead() const
400 // we can read if there's something in the put back buffer
401 // even pipe is closed
402 if ( m_wbacksize
> m_wbackcur
)
405 wxPipeInputStream
* const self
= wxConstCast(this, wxPipeInputStream
);
409 // set back to mark Eof as it may have been unset by Ungetch()
410 self
->m_lasterror
= wxSTREAM_EOF
;
416 // function name is misleading, it works with anon pipes as well
417 DWORD rc
= ::PeekNamedPipe
420 NULL
, 0, // ptr to buffer and its size
421 NULL
, // [out] bytes read
422 &nAvailable
, // [out] bytes available
423 NULL
// [out] bytes left
428 if ( ::GetLastError() != ERROR_BROKEN_PIPE
)
431 wxLogLastError(wxT("PeekNamedPipe"));
434 // don't try to continue reading from a pipe if an error occurred or if
435 // it had been closed
436 ::CloseHandle(m_hInput
);
438 self
->m_hInput
= INVALID_HANDLE_VALUE
;
439 self
->m_lasterror
= wxSTREAM_EOF
;
444 return nAvailable
!= 0;
447 size_t wxPipeInputStream::OnSysRead(void *buffer
, size_t len
)
451 m_lasterror
= wxSTREAM_EOF
;
457 if ( !::ReadFile(m_hInput
, buffer
, len
, &bytesRead
, NULL
) )
459 m_lasterror
= ::GetLastError() == ERROR_BROKEN_PIPE
461 : wxSTREAM_READ_ERROR
;
464 // bytesRead is set to 0, as desired, if an error occurred
468 // ----------------------------------------------------------------------------
469 // wxPipeOutputStream
470 // ----------------------------------------------------------------------------
472 wxPipeOutputStream::wxPipeOutputStream(HANDLE hOutput
)
476 // unblock the pipe to prevent deadlocks when we're writing to the pipe
477 // from which the child process can't read because it is writing in its own
479 DWORD mode
= PIPE_READMODE_BYTE
| PIPE_NOWAIT
;
480 if ( !::SetNamedPipeHandleState
484 NULL
, // collection count (we don't set it)
485 NULL
// timeout (we don't set it neither)
488 wxLogLastError(wxT("SetNamedPipeHandleState(PIPE_NOWAIT)"));
492 bool wxPipeOutputStream::Close()
494 return ::CloseHandle(m_hOutput
) != 0;
498 size_t wxPipeOutputStream::OnSysWrite(const void *buffer
, size_t len
)
500 m_lasterror
= wxSTREAM_NO_ERROR
;
502 DWORD totalWritten
= 0;
506 if ( !::WriteFile(m_hOutput
, buffer
, len
, &chunkWritten
, NULL
) )
508 m_lasterror
= ::GetLastError() == ERROR_BROKEN_PIPE
510 : wxSTREAM_WRITE_ERROR
;
517 buffer
= (char *)buffer
+ chunkWritten
;
518 totalWritten
+= chunkWritten
;
525 #endif // wxUSE_STREAMS
527 // ============================================================================
528 // wxExecute functions family
529 // ============================================================================
533 // connect to the given server via DDE and ask it to execute the command
535 wxExecuteDDE(const wxString
& ddeServer
,
536 const wxString
& ddeTopic
,
537 const wxString
& ddeCommand
)
539 bool ok
wxDUMMY_INITIALIZE(false);
543 conn
= client
.MakeConnection(wxEmptyString
, ddeServer
, ddeTopic
);
548 else // connected to DDE server
550 // the added complication here is that although most programs use
551 // XTYP_EXECUTE for their DDE API, some important ones -- like Word
552 // and other MS stuff - use XTYP_REQUEST!
554 // moreover, anotheri mportant program (IE) understands both but
555 // returns an error from Execute() so we must try Request() first
556 // to avoid doing it twice
558 // we're prepared for this one to fail, so don't show errors
561 ok
= conn
->Request(ddeCommand
) != NULL
;
566 // now try execute -- but show the errors
567 ok
= conn
->Execute(ddeCommand
);
576 long wxExecute(const wxString
& cmd
, int flags
, wxProcess
*handler
,
577 const wxExecuteEnv
*env
)
579 wxCHECK_MSG( !cmd
.empty(), 0, wxT("empty command in wxExecute") );
582 // for many reasons, the code below breaks down if it's called from another
583 // thread -- this could be fixed, but as Unix versions don't support this
584 // neither I don't want to waste time on this now
585 wxASSERT_MSG( wxThread::IsMain(),
586 wxT("wxExecute() can be called only from the main thread") );
587 #endif // wxUSE_THREADS
592 // DDE hack: this is really not pretty, but we need to allow this for
593 // transparent handling of DDE servers in wxMimeTypesManager. Usually it
594 // returns the command which should be run to view/open/... a file of the
595 // given type. Sometimes, however, this command just launches the server
596 // and an additional DDE request must be made to really open the file. To
597 // keep all this well hidden from the application, we allow a special form
598 // of command: WX_DDE#<command>#DDE_SERVER#DDE_TOPIC#DDE_COMMAND in which
599 // case we execute just <command> and process the rest below
600 wxString ddeServer
, ddeTopic
, ddeCommand
;
601 static const size_t lenDdePrefix
= 7; // strlen("WX_DDE:")
602 if ( cmd
.Left(lenDdePrefix
) == wxT("WX_DDE#") )
604 // speed up the concatenations below
605 ddeServer
.reserve(256);
606 ddeTopic
.reserve(256);
607 ddeCommand
.reserve(256);
609 const wxChar
*p
= cmd
.c_str() + 7;
610 while ( *p
&& *p
!= wxT('#') )
622 wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute"));
625 while ( *p
&& *p
!= wxT('#') )
637 wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute"));
640 while ( *p
&& *p
!= wxT('#') )
652 wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute"));
660 // if we want to just launch the program and not wait for its
661 // termination, try to execute DDE command right now, it can succeed if
662 // the process is already running - but as it fails if it's not
663 // running, suppress any errors it might generate
664 if ( !(flags
& wxEXEC_SYNC
) )
667 if ( wxExecuteDDE(ddeServer
, ddeTopic
, ddeCommand
) )
669 // a dummy PID - this is a hack, of course, but it's well worth
670 // it as we don't open a new server each time we're called
671 // which would be quite bad
683 // the IO redirection is only supported with wxUSE_STREAMS
684 BOOL redirect
= FALSE
;
686 #if wxUSE_STREAMS && !defined(__WXWINCE__)
687 wxPipe pipeIn
, pipeOut
, pipeErr
;
689 // we'll save here the copy of pipeIn[Write]
690 HANDLE hpipeStdinWrite
= INVALID_HANDLE_VALUE
;
692 // open the pipes to which child process IO will be redirected if needed
693 if ( handler
&& handler
->IsRedirected() )
695 // create pipes for redirecting stdin, stdout and stderr
696 if ( !pipeIn
.Create() || !pipeOut
.Create() || !pipeErr
.Create() )
698 wxLogSysError(_("Failed to redirect the child process IO"));
700 // indicate failure: we need to return different error code
701 // depending on the sync flag
702 return flags
& wxEXEC_SYNC
? -1 : 0;
707 #endif // wxUSE_STREAMS
709 // create the process
714 #if wxUSE_STREAMS && !defined(__WXWINCE__)
717 si
.dwFlags
= STARTF_USESTDHANDLES
;
719 si
.hStdInput
= pipeIn
[wxPipe::Read
];
720 si
.hStdOutput
= pipeOut
[wxPipe::Write
];
721 si
.hStdError
= pipeErr
[wxPipe::Write
];
723 // we must duplicate the handle to the write side of stdin pipe to make
724 // it non inheritable: indeed, we must close the writing end of pipeIn
725 // before launching the child process as otherwise this handle will be
726 // inherited by the child which will never close it and so the pipe
727 // will never be closed and the child will be left stuck in ReadFile()
728 HANDLE pipeInWrite
= pipeIn
.Detach(wxPipe::Write
);
729 if ( !::DuplicateHandle
731 ::GetCurrentProcess(),
733 ::GetCurrentProcess(),
735 0, // desired access: unused here
736 FALSE
, // not inherited
737 DUPLICATE_SAME_ACCESS
// same access as for src handle
740 wxLogLastError(wxT("DuplicateHandle"));
743 ::CloseHandle(pipeInWrite
);
745 #endif // wxUSE_STREAMS
747 // The default logic for showing the console is to show it only if the IO
748 // is not redirected however wxEXEC_{SHOW,HIDE}_CONSOLE flags can be
749 // explicitly specified to change it.
750 if ( (flags
& wxEXEC_HIDE_CONSOLE
) ||
751 (redirect
&& !(flags
& wxEXEC_SHOW_CONSOLE
)) )
753 si
.dwFlags
|= STARTF_USESHOWWINDOW
;
754 si
.wShowWindow
= SW_HIDE
;
758 PROCESS_INFORMATION pi
;
759 DWORD dwFlags
= CREATE_SUSPENDED
;
762 if ( (flags
& wxEXEC_MAKE_GROUP_LEADER
) &&
763 (wxGetOsVersion() == wxOS_WINDOWS_NT
) )
764 dwFlags
|= CREATE_NEW_PROCESS_GROUP
;
766 dwFlags
|= CREATE_DEFAULT_ERROR_MODE
;
768 // we are assuming commands without spaces for now
769 wxString moduleName
= command
.BeforeFirst(wxT(' '));
770 wxString arguments
= command
.AfterFirst(wxT(' '));
773 wxWxCharBuffer envBuffer
;
777 useCwd
= !env
->cwd
.empty();
779 // Translate environment variable map into NUL-terminated list of
780 // NUL-terminated strings.
781 if ( !env
->env
.empty() )
784 // Environment variables can contain non-ASCII characters. We could
785 // check for it and not use this flag if everything is really ASCII
786 // only but there doesn't seem to be any reason to do it so just
787 // assume Unicode by default.
788 dwFlags
|= CREATE_UNICODE_ENVIRONMENT
;
789 #endif // wxUSE_UNICODE
791 wxEnvVariableHashMap::const_iterator it
;
793 size_t envSz
= 1; // ending '\0'
794 for ( it
= env
->env
.begin(); it
!= env
->env
.end(); ++it
)
796 // Add size of env variable name and value, and '=' char and
798 envSz
+= it
->first
.length() + it
->second
.length() + 2;
801 envBuffer
.extend(envSz
);
803 wxChar
*p
= envBuffer
.data();
804 for ( it
= env
->env
.begin(); it
!= env
->env
.end(); ++it
)
806 const wxString line
= it
->first
+ wxS("=") + it
->second
;
808 // Include the trailing NUL which will always terminate the
809 // buffer returned by t_str().
810 const size_t len
= line
.length() + 1;
812 wxTmemcpy(p
, line
.t_str(), len
);
817 // And another NUL to terminate the list of NUL-terminated strings.
822 // Translate wxWidgets priority to Windows conventions.
825 unsigned prio
= handler
->GetPriority();
827 dwFlags
|= IDLE_PRIORITY_CLASS
;
828 else if ( prio
<= 40 )
829 dwFlags
|= BELOW_NORMAL_PRIORITY_CLASS
;
830 else if ( prio
<= 60 )
831 dwFlags
|= NORMAL_PRIORITY_CLASS
;
832 else if ( prio
<= 80 )
833 dwFlags
|= ABOVE_NORMAL_PRIORITY_CLASS
;
834 else if ( prio
<= 99 )
835 dwFlags
|= HIGH_PRIORITY_CLASS
;
836 else if ( prio
<= 100 )
837 dwFlags
|= REALTIME_PRIORITY_CLASS
;
840 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
841 dwFlags
|= NORMAL_PRIORITY_CLASS
;
845 bool ok
= ::CreateProcess
847 // WinCE requires appname to be non null
848 // Win32 allows for null
850 moduleName
.t_str(), // application name
851 wxMSW_CONV_LPTSTR(arguments
), // arguments
853 NULL
, // application name (use only cmd line)
854 wxMSW_CONV_LPTSTR(command
), // full command line
856 NULL
, // security attributes: defaults for both
857 NULL
, // the process and its main thread
858 redirect
, // inherit handles if we use pipes
859 dwFlags
, // process creation flags
860 envBuffer
.data(), // environment (may be NULL which is fine)
861 useCwd
// initial working directory
862 ? wxMSW_CONV_LPTSTR(env
->cwd
)
863 : NULL
, // (or use the same)
864 &si
, // startup info (unused here)
868 #if wxUSE_STREAMS && !defined(__WXWINCE__)
869 // we can close the pipe ends used by child anyhow
872 ::CloseHandle(pipeIn
.Detach(wxPipe::Read
));
873 ::CloseHandle(pipeOut
.Detach(wxPipe::Write
));
874 ::CloseHandle(pipeErr
.Detach(wxPipe::Write
));
876 #endif // wxUSE_STREAMS
880 #if wxUSE_STREAMS && !defined(__WXWINCE__)
881 // close the other handles too
884 ::CloseHandle(pipeOut
.Detach(wxPipe::Read
));
885 ::CloseHandle(pipeErr
.Detach(wxPipe::Read
));
887 #endif // wxUSE_STREAMS
889 wxLogSysError(_("Execution of command '%s' failed"), command
.c_str());
891 return flags
& wxEXEC_SYNC
? -1 : 0;
894 #if wxUSE_STREAMS && !defined(__WXWINCE__)
895 // the input buffer bufOut is connected to stdout, this is why it is
896 // called bufOut and not bufIn
897 wxStreamTempInputBuffer bufOut
,
902 // We can now initialize the wxStreams
904 outStream
= new wxPipeInputStream(pipeOut
.Detach(wxPipe::Read
));
906 errStream
= new wxPipeInputStream(pipeErr
.Detach(wxPipe::Read
));
908 inStream
= new wxPipeOutputStream(hpipeStdinWrite
);
910 handler
->SetPipeStreams(outStream
, inStream
, errStream
);
912 bufOut
.Init(outStream
);
913 bufErr
.Init(errStream
);
915 #endif // wxUSE_STREAMS
917 // create a hidden window to receive notification about process
919 HWND hwnd
= wxCreateHiddenWindow
921 &gs_classForHiddenWindow
,
922 wxMSWEXEC_WNDCLASSNAME
,
923 (WNDPROC
)wxExecuteWindowCbk
926 wxASSERT_MSG( hwnd
, wxT("can't create a hidden window for wxExecute") );
929 wxExecuteData
*data
= new wxExecuteData
;
930 data
->hProcess
= pi
.hProcess
;
931 data
->dwProcessId
= pi
.dwProcessId
;
933 data
->state
= (flags
& wxEXEC_SYNC
) != 0;
934 if ( flags
& wxEXEC_SYNC
)
936 // handler may be !NULL for capturing program output, but we don't use
937 // it wxExecuteData struct in this case
938 data
->handler
= NULL
;
942 // may be NULL or not
943 data
->handler
= handler
;
946 handler
->SetPid(pi
.dwProcessId
);
950 HANDLE hThread
= ::CreateThread(NULL
,
957 // resume process we created now - whether the thread creation succeeded or
959 if ( ::ResumeThread(pi
.hThread
) == (DWORD
)-1 )
961 // ignore it - what can we do?
962 wxLogLastError(wxT("ResumeThread in wxExecute"));
965 // close unneeded handle
966 if ( !::CloseHandle(pi
.hThread
) )
968 wxLogLastError(wxT("CloseHandle(hThread)"));
973 wxLogLastError(wxT("CreateThread in wxExecute"));
978 // the process still started up successfully...
979 return pi
.dwProcessId
;
982 gs_asyncThreads
.push_back(hThread
);
984 #if wxUSE_IPC && !defined(__WXWINCE__)
985 // second part of DDE hack: now establish the DDE conversation with the
986 // just launched process
987 if ( !ddeServer
.empty() )
991 // give the process the time to init itself
993 // we use a very big timeout hoping that WaitForInputIdle() will return
994 // much sooner, but not INFINITE just in case the process hangs
995 // completely - like this we will regain control sooner or later
996 switch ( ::WaitForInputIdle(pi
.hProcess
, 10000 /* 10 seconds */) )
999 wxFAIL_MSG( wxT("unexpected WaitForInputIdle() return code") );
1003 wxLogLastError(wxT("WaitForInputIdle() in wxExecute"));
1006 wxLogDebug(wxT("Timeout too small in WaitForInputIdle"));
1012 // ok, process ready to accept DDE requests
1013 ddeOK
= wxExecuteDDE(ddeServer
, ddeTopic
, ddeCommand
);
1018 wxLogDebug(wxT("Failed to send DDE request to the process \"%s\"."),
1024 if ( !(flags
& wxEXEC_SYNC
) )
1026 // clean up will be done when the process terminates
1029 return pi
.dwProcessId
;
1032 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
1033 wxCHECK_MSG( traits
, -1, wxT("no wxAppTraits in wxExecute()?") );
1035 void *cookie
= NULL
;
1036 if ( !(flags
& wxEXEC_NODISABLE
) )
1038 // disable all app windows while waiting for the child process to finish
1039 cookie
= traits
->BeforeChildWaitLoop();
1042 // wait until the child process terminates
1043 while ( data
->state
)
1045 #if wxUSE_STREAMS && !defined(__WXWINCE__)
1046 if ( !bufOut
.Update() && !bufErr
.Update() )
1047 #endif // wxUSE_STREAMS
1049 // don't eat 100% of the CPU -- ugly but anything else requires
1050 // real async IO which we don't have for the moment
1054 // we must always process messages for our hidden window or we'd never
1055 // get wxWM_PROC_TERMINATED and so this loop would never terminate
1057 ::PeekMessage(&msg
, data
->hWnd
, 0, 0, PM_REMOVE
);
1059 // we may also need to process messages for all the other application
1061 if ( !(flags
& wxEXEC_NOEVENTS
) )
1063 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
1069 if ( !(flags
& wxEXEC_NODISABLE
) )
1071 // reenable disabled windows back
1072 traits
->AfterChildWaitLoop(cookie
);
1075 DWORD dwExitCode
= data
->dwExitCode
;
1078 // return the exit code
1082 template <typename CharType
>
1083 long wxExecuteImpl(CharType
**argv
, int flags
, wxProcess
*handler
,
1084 const wxExecuteEnv
*env
)
1087 command
.reserve(1024);
1097 // we need to quote empty arguments, otherwise they'd just
1103 // escape any quotes present in the string to avoid interfering
1104 // with the command line parsing in the child process
1105 arg
.Replace("\"", "\\\"", true /* replace all */);
1107 // and quote any arguments containing the spaces to prevent them from
1108 // being broken down
1109 quote
= arg
.find_first_of(" \t") != wxString::npos
;
1113 command
+= '\"' + arg
+ '\"';
1123 return wxExecute(command
, flags
, handler
, env
);
1126 long wxExecute(char **argv
, int flags
, wxProcess
*handler
,
1127 const wxExecuteEnv
*env
)
1129 return wxExecuteImpl(argv
, flags
, handler
, env
);
1134 long wxExecute(wchar_t **argv
, int flags
, wxProcess
*handler
,
1135 const wxExecuteEnv
*env
)
1137 return wxExecuteImpl(argv
, flags
, handler
, env
);
1140 #endif // wxUSE_UNICODE