1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/utilsexc.cpp
3 // Purpose: wxExecute implementation for MSW
4 // Author: Julian Smart
7 // Copyright: (c) 1998-2002 wxWidgets dev team
8 // Licence: wxWindows licence
9 /////////////////////////////////////////////////////////////////////////////
11 // ============================================================================
13 // ============================================================================
15 // ----------------------------------------------------------------------------
17 // ----------------------------------------------------------------------------
19 // For compilers that support precompilation, includes "wx.h".
20 #include "wx/wxprec.h"
32 #include "wx/stream.h"
34 #include "wx/module.h"
37 #include "wx/process.h"
38 #include "wx/thread.h"
39 #include "wx/apptrait.h"
40 #include "wx/evtloop.h"
41 #include "wx/vector.h"
44 #include "wx/msw/private.h"
48 #if !defined(__GNUWIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
53 #if defined(__GNUWIN32__)
54 #include <sys/unistd.h>
58 #if !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
72 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
79 #include "wx/dde.h" // for WX_DDE hack in wxExecute
82 #include "wx/msw/private/hiddenwin.h"
84 // FIXME-VC6: These are not defined in VC6 SDK headers.
85 #ifndef BELOW_NORMAL_PRIORITY_CLASS
86 #define BELOW_NORMAL_PRIORITY_CLASS 0x4000
89 #ifndef ABOVE_NORMAL_PRIORITY_CLASS
90 #define ABOVE_NORMAL_PRIORITY_CLASS 0x8000
93 // ----------------------------------------------------------------------------
95 // ----------------------------------------------------------------------------
97 // this message is sent when the process we're waiting for terminates
98 #define wxWM_PROC_TERMINATED (WM_USER + 10000)
100 // ----------------------------------------------------------------------------
101 // this module globals
102 // ----------------------------------------------------------------------------
104 // we need to create a hidden window to receive the process termination
105 // notifications and for this we need a (Win) class name for it which we will
106 // register the first time it's needed
107 static const wxChar
*wxMSWEXEC_WNDCLASSNAME
= wxT("_wxExecute_Internal_Class");
108 static const wxChar
*gs_classForHiddenWindow
= NULL
;
110 // event used to wake up threads waiting in wxExecuteThread
111 static HANDLE gs_heventShutdown
= NULL
;
113 // handles of all threads monitoring the execution of asynchronously running
115 static wxVector
<HANDLE
> gs_asyncThreads
;
117 // ----------------------------------------------------------------------------
119 // ----------------------------------------------------------------------------
121 // structure describing the process we're being waiting for
127 if ( !::CloseHandle(hProcess
) )
129 wxLogLastError(wxT("CloseHandle(hProcess)"));
133 HWND hWnd
; // window to send wxWM_PROC_TERMINATED to
134 HANDLE hProcess
; // handle of the process
135 DWORD dwProcessId
; // pid of the process
137 DWORD dwExitCode
; // the exit code of the process
138 bool state
; // set to false when the process finishes
141 class wxExecuteModule
: public wxModule
144 virtual bool OnInit() { return true; }
145 virtual void OnExit()
147 if ( gs_heventShutdown
)
149 // stop any threads waiting for the termination of asynchronously
151 if ( !::SetEvent(gs_heventShutdown
) )
153 wxLogDebug(wxT("Failed to set shutdown event in wxExecuteModule"));
156 ::CloseHandle(gs_heventShutdown
);
157 gs_heventShutdown
= NULL
;
159 // now wait until they terminate
160 if ( !gs_asyncThreads
.empty() )
162 const size_t numThreads
= gs_asyncThreads
.size();
164 if ( ::WaitForMultipleObjects
168 TRUE
, // wait for all of them to become signalled
169 3000 // long but finite value
172 wxLogDebug(wxT("Failed to stop all wxExecute monitor threads"));
175 for ( size_t n
= 0; n
< numThreads
; n
++ )
177 ::CloseHandle(gs_asyncThreads
[n
]);
180 gs_asyncThreads
.clear();
184 if ( gs_classForHiddenWindow
)
186 if ( !::UnregisterClass(wxMSWEXEC_WNDCLASSNAME
, wxGetInstance()) )
188 wxLogLastError(wxT("UnregisterClass(wxExecClass)"));
191 gs_classForHiddenWindow
= NULL
;
196 DECLARE_DYNAMIC_CLASS(wxExecuteModule
)
199 IMPLEMENT_DYNAMIC_CLASS(wxExecuteModule
, wxModule
)
201 #if wxUSE_STREAMS && !defined(__WXWINCE__)
203 #include "wx/private/pipestream.h"
204 #include "wx/private/streamtempinput.h"
206 // ----------------------------------------------------------------------------
207 // wxPipe represents a Win32 anonymous pipe
208 // ----------------------------------------------------------------------------
213 // the symbolic names for the pipe ends
220 // default ctor doesn't do anything
221 wxPipe() { m_handles
[Read
] = m_handles
[Write
] = INVALID_HANDLE_VALUE
; }
223 // create the pipe, return true if ok, false on error
226 // default secutiry attributes
227 SECURITY_ATTRIBUTES security
;
229 security
.nLength
= sizeof(security
);
230 security
.lpSecurityDescriptor
= NULL
;
231 security
.bInheritHandle
= TRUE
; // to pass it to the child
233 if ( !::CreatePipe(&m_handles
[0], &m_handles
[1], &security
, 0) )
235 wxLogSysError(_("Failed to create an anonymous pipe"));
243 // return true if we were created successfully
244 bool IsOk() const { return m_handles
[Read
] != INVALID_HANDLE_VALUE
; }
246 // return the descriptor for one of the pipe ends
247 HANDLE
operator[](Direction which
) const { return m_handles
[which
]; }
249 // detach a descriptor, meaning that the pipe dtor won't close it, and
251 HANDLE
Detach(Direction which
)
253 HANDLE handle
= m_handles
[which
];
254 m_handles
[which
] = INVALID_HANDLE_VALUE
;
259 // close the pipe descriptors
262 for ( size_t n
= 0; n
< WXSIZEOF(m_handles
); n
++ )
264 if ( m_handles
[n
] != INVALID_HANDLE_VALUE
)
266 ::CloseHandle(m_handles
[n
]);
267 m_handles
[n
] = INVALID_HANDLE_VALUE
;
272 // dtor closes the pipe descriptors
273 ~wxPipe() { Close(); }
279 #endif // wxUSE_STREAMS
281 // ============================================================================
283 // ============================================================================
285 // ----------------------------------------------------------------------------
286 // process termination detecting support
287 // ----------------------------------------------------------------------------
289 // thread function for the thread monitoring the process termination
290 static DWORD __stdcall
wxExecuteThread(void *arg
)
292 wxExecuteData
* const data
= (wxExecuteData
*)arg
;
294 // create the shutdown event if we're the first thread starting to wait
295 if ( !gs_heventShutdown
)
297 // create a manual initially non-signalled event object
298 gs_heventShutdown
= ::CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
299 if ( !gs_heventShutdown
)
301 wxLogDebug(wxT("CreateEvent() in wxExecuteThread failed"));
305 HANDLE handles
[2] = { data
->hProcess
, gs_heventShutdown
};
306 switch ( ::WaitForMultipleObjects(2, handles
, FALSE
, INFINITE
) )
309 // process terminated, get its exit code
310 if ( !::GetExitCodeProcess(data
->hProcess
, &data
->dwExitCode
) )
312 wxLogLastError(wxT("GetExitCodeProcess"));
315 wxASSERT_MSG( data
->dwExitCode
!= STILL_ACTIVE
,
316 wxT("process should have terminated") );
318 // send a message indicating process termination to the window
319 ::SendMessage(data
->hWnd
, wxWM_PROC_TERMINATED
, 0, (LPARAM
)data
);
322 case WAIT_OBJECT_0
+ 1:
323 // we're shutting down but the process is still running -- leave it
324 // run but clean up the associated data
329 //else: exiting while synchronously executing process is still
330 // running? this shouldn't happen...
334 wxLogDebug(wxT("Waiting for the process termination failed!"));
340 // window procedure of a hidden window which is created just to receive
341 // the notification message when a process exits
342 LRESULT APIENTRY _EXPORT
wxExecuteWindowCbk(HWND hWnd
, UINT message
,
343 WPARAM wParam
, LPARAM lParam
)
345 if ( message
== wxWM_PROC_TERMINATED
)
347 DestroyWindow(hWnd
); // we don't need it any more
349 wxExecuteData
* const data
= (wxExecuteData
*)lParam
;
352 data
->handler
->OnTerminate((int)data
->dwProcessId
,
353 (int)data
->dwExitCode
);
358 // we're executing synchronously, tell the waiting thread
359 // that the process finished
364 // asynchronous execution - we should do the clean up
372 return ::DefWindowProc(hWnd
, message
, wParam
, lParam
);
376 // ============================================================================
377 // implementation of IO redirection support classes
378 // ============================================================================
380 #if wxUSE_STREAMS && !defined(__WXWINCE__)
382 // ----------------------------------------------------------------------------
383 // wxPipeInputStreams
384 // ----------------------------------------------------------------------------
386 wxPipeInputStream::wxPipeInputStream(HANDLE hInput
)
391 wxPipeInputStream::~wxPipeInputStream()
393 if ( m_hInput
!= INVALID_HANDLE_VALUE
)
394 ::CloseHandle(m_hInput
);
397 bool wxPipeInputStream::CanRead() const
399 // we can read if there's something in the put back buffer
400 // even pipe is closed
401 if ( m_wbacksize
> m_wbackcur
)
404 wxPipeInputStream
* const self
= wxConstCast(this, wxPipeInputStream
);
408 // set back to mark Eof as it may have been unset by Ungetch()
409 self
->m_lasterror
= wxSTREAM_EOF
;
415 // function name is misleading, it works with anon pipes as well
416 DWORD rc
= ::PeekNamedPipe
419 NULL
, 0, // ptr to buffer and its size
420 NULL
, // [out] bytes read
421 &nAvailable
, // [out] bytes available
422 NULL
// [out] bytes left
427 if ( ::GetLastError() != ERROR_BROKEN_PIPE
)
430 wxLogLastError(wxT("PeekNamedPipe"));
433 // don't try to continue reading from a pipe if an error occurred or if
434 // it had been closed
435 ::CloseHandle(m_hInput
);
437 self
->m_hInput
= INVALID_HANDLE_VALUE
;
438 self
->m_lasterror
= wxSTREAM_EOF
;
443 return nAvailable
!= 0;
446 size_t wxPipeInputStream::OnSysRead(void *buffer
, size_t len
)
450 m_lasterror
= wxSTREAM_EOF
;
456 if ( !::ReadFile(m_hInput
, buffer
, len
, &bytesRead
, NULL
) )
458 m_lasterror
= ::GetLastError() == ERROR_BROKEN_PIPE
460 : wxSTREAM_READ_ERROR
;
463 // bytesRead is set to 0, as desired, if an error occurred
467 // ----------------------------------------------------------------------------
468 // wxPipeOutputStream
469 // ----------------------------------------------------------------------------
471 wxPipeOutputStream::wxPipeOutputStream(HANDLE hOutput
)
475 // unblock the pipe to prevent deadlocks when we're writing to the pipe
476 // from which the child process can't read because it is writing in its own
478 DWORD mode
= PIPE_READMODE_BYTE
| PIPE_NOWAIT
;
479 if ( !::SetNamedPipeHandleState
483 NULL
, // collection count (we don't set it)
484 NULL
// timeout (we don't set it neither)
487 wxLogLastError(wxT("SetNamedPipeHandleState(PIPE_NOWAIT)"));
491 bool wxPipeOutputStream::Close()
493 return ::CloseHandle(m_hOutput
) != 0;
497 size_t wxPipeOutputStream::OnSysWrite(const void *buffer
, size_t len
)
499 m_lasterror
= wxSTREAM_NO_ERROR
;
501 DWORD totalWritten
= 0;
505 if ( !::WriteFile(m_hOutput
, buffer
, len
, &chunkWritten
, NULL
) )
507 m_lasterror
= ::GetLastError() == ERROR_BROKEN_PIPE
509 : wxSTREAM_WRITE_ERROR
;
516 buffer
= (char *)buffer
+ chunkWritten
;
517 totalWritten
+= chunkWritten
;
524 #endif // wxUSE_STREAMS
526 // ============================================================================
527 // wxExecute functions family
528 // ============================================================================
532 // connect to the given server via DDE and ask it to execute the command
534 wxExecuteDDE(const wxString
& ddeServer
,
535 const wxString
& ddeTopic
,
536 const wxString
& ddeCommand
)
538 bool ok
wxDUMMY_INITIALIZE(false);
542 conn
= client
.MakeConnection(wxEmptyString
, ddeServer
, ddeTopic
);
547 else // connected to DDE server
549 // the added complication here is that although most programs use
550 // XTYP_EXECUTE for their DDE API, some important ones -- like Word
551 // and other MS stuff - use XTYP_REQUEST!
553 // moreover, anotheri mportant program (IE) understands both but
554 // returns an error from Execute() so we must try Request() first
555 // to avoid doing it twice
557 // we're prepared for this one to fail, so don't show errors
560 ok
= conn
->Request(ddeCommand
) != NULL
;
565 // now try execute -- but show the errors
566 ok
= conn
->Execute(ddeCommand
);
575 long wxExecute(const wxString
& cmd
, int flags
, wxProcess
*handler
,
576 const wxExecuteEnv
*env
)
578 wxCHECK_MSG( !cmd
.empty(), 0, wxT("empty command in wxExecute") );
581 // for many reasons, the code below breaks down if it's called from another
582 // thread -- this could be fixed, but as Unix versions don't support this
583 // neither I don't want to waste time on this now
584 wxASSERT_MSG( wxThread::IsMain(),
585 wxT("wxExecute() can be called only from the main thread") );
586 #endif // wxUSE_THREADS
591 // DDE hack: this is really not pretty, but we need to allow this for
592 // transparent handling of DDE servers in wxMimeTypesManager. Usually it
593 // returns the command which should be run to view/open/... a file of the
594 // given type. Sometimes, however, this command just launches the server
595 // and an additional DDE request must be made to really open the file. To
596 // keep all this well hidden from the application, we allow a special form
597 // of command: WX_DDE#<command>#DDE_SERVER#DDE_TOPIC#DDE_COMMAND in which
598 // case we execute just <command> and process the rest below
599 wxString ddeServer
, ddeTopic
, ddeCommand
;
600 static const size_t lenDdePrefix
= 7; // strlen("WX_DDE:")
601 if ( cmd
.Left(lenDdePrefix
) == wxT("WX_DDE#") )
603 // speed up the concatenations below
604 ddeServer
.reserve(256);
605 ddeTopic
.reserve(256);
606 ddeCommand
.reserve(256);
608 const wxChar
*p
= cmd
.c_str() + 7;
609 while ( *p
&& *p
!= wxT('#') )
621 wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute"));
624 while ( *p
&& *p
!= wxT('#') )
636 wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute"));
639 while ( *p
&& *p
!= wxT('#') )
651 wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute"));
659 // if we want to just launch the program and not wait for its
660 // termination, try to execute DDE command right now, it can succeed if
661 // the process is already running - but as it fails if it's not
662 // running, suppress any errors it might generate
663 if ( !(flags
& wxEXEC_SYNC
) )
666 if ( wxExecuteDDE(ddeServer
, ddeTopic
, ddeCommand
) )
668 // a dummy PID - this is a hack, of course, but it's well worth
669 // it as we don't open a new server each time we're called
670 // which would be quite bad
682 // the IO redirection is only supported with wxUSE_STREAMS
683 BOOL redirect
= FALSE
;
685 #if wxUSE_STREAMS && !defined(__WXWINCE__)
686 wxPipe pipeIn
, pipeOut
, pipeErr
;
688 // we'll save here the copy of pipeIn[Write]
689 HANDLE hpipeStdinWrite
= INVALID_HANDLE_VALUE
;
691 // open the pipes to which child process IO will be redirected if needed
692 if ( handler
&& handler
->IsRedirected() )
694 // create pipes for redirecting stdin, stdout and stderr
695 if ( !pipeIn
.Create() || !pipeOut
.Create() || !pipeErr
.Create() )
697 wxLogSysError(_("Failed to redirect the child process IO"));
699 // indicate failure: we need to return different error code
700 // depending on the sync flag
701 return flags
& wxEXEC_SYNC
? -1 : 0;
706 #endif // wxUSE_STREAMS
708 // create the process
713 #if wxUSE_STREAMS && !defined(__WXWINCE__)
716 si
.dwFlags
= STARTF_USESTDHANDLES
;
718 si
.hStdInput
= pipeIn
[wxPipe::Read
];
719 si
.hStdOutput
= pipeOut
[wxPipe::Write
];
720 si
.hStdError
= pipeErr
[wxPipe::Write
];
722 // we must duplicate the handle to the write side of stdin pipe to make
723 // it non inheritable: indeed, we must close the writing end of pipeIn
724 // before launching the child process as otherwise this handle will be
725 // inherited by the child which will never close it and so the pipe
726 // will never be closed and the child will be left stuck in ReadFile()
727 HANDLE pipeInWrite
= pipeIn
.Detach(wxPipe::Write
);
728 if ( !::DuplicateHandle
730 ::GetCurrentProcess(),
732 ::GetCurrentProcess(),
734 0, // desired access: unused here
735 FALSE
, // not inherited
736 DUPLICATE_SAME_ACCESS
// same access as for src handle
739 wxLogLastError(wxT("DuplicateHandle"));
742 ::CloseHandle(pipeInWrite
);
744 #endif // wxUSE_STREAMS
746 // The default logic for showing the console is to show it only if the IO
747 // is not redirected however wxEXEC_{SHOW,HIDE}_CONSOLE flags can be
748 // explicitly specified to change it.
749 if ( (flags
& wxEXEC_HIDE_CONSOLE
) ||
750 (redirect
&& !(flags
& wxEXEC_SHOW_CONSOLE
)) )
752 si
.dwFlags
|= STARTF_USESHOWWINDOW
;
753 si
.wShowWindow
= SW_HIDE
;
757 PROCESS_INFORMATION pi
;
758 DWORD dwFlags
= CREATE_SUSPENDED
;
761 if ( (flags
& wxEXEC_MAKE_GROUP_LEADER
) &&
762 (wxGetOsVersion() == wxOS_WINDOWS_NT
) )
763 dwFlags
|= CREATE_NEW_PROCESS_GROUP
;
765 dwFlags
|= CREATE_DEFAULT_ERROR_MODE
;
767 // we are assuming commands without spaces for now
768 wxString moduleName
= command
.BeforeFirst(wxT(' '));
769 wxString arguments
= command
.AfterFirst(wxT(' '));
772 wxWxCharBuffer envBuffer
;
776 useCwd
= !env
->cwd
.empty();
778 // Translate environment variable map into NUL-terminated list of
779 // NUL-terminated strings.
780 if ( !env
->env
.empty() )
783 // Environment variables can contain non-ASCII characters. We could
784 // check for it and not use this flag if everything is really ASCII
785 // only but there doesn't seem to be any reason to do it so just
786 // assume Unicode by default.
787 dwFlags
|= CREATE_UNICODE_ENVIRONMENT
;
788 #endif // wxUSE_UNICODE
790 wxEnvVariableHashMap::const_iterator it
;
792 size_t envSz
= 1; // ending '\0'
793 for ( it
= env
->env
.begin(); it
!= env
->env
.end(); ++it
)
795 // Add size of env variable name and value, and '=' char and
797 envSz
+= it
->first
.length() + it
->second
.length() + 2;
800 envBuffer
.extend(envSz
);
802 wxChar
*p
= envBuffer
.data();
803 for ( it
= env
->env
.begin(); it
!= env
->env
.end(); ++it
)
805 const wxString line
= it
->first
+ wxS("=") + it
->second
;
807 // Include the trailing NUL which will always terminate the
808 // buffer returned by t_str().
809 const size_t len
= line
.length() + 1;
811 wxTmemcpy(p
, line
.t_str(), len
);
816 // And another NUL to terminate the list of NUL-terminated strings.
821 // Translate wxWidgets priority to Windows conventions.
824 unsigned prio
= handler
->GetPriority();
826 dwFlags
|= IDLE_PRIORITY_CLASS
;
827 else if ( prio
<= 40 )
828 dwFlags
|= BELOW_NORMAL_PRIORITY_CLASS
;
829 else if ( prio
<= 60 )
830 dwFlags
|= NORMAL_PRIORITY_CLASS
;
831 else if ( prio
<= 80 )
832 dwFlags
|= ABOVE_NORMAL_PRIORITY_CLASS
;
833 else if ( prio
<= 99 )
834 dwFlags
|= HIGH_PRIORITY_CLASS
;
835 else if ( prio
<= 100 )
836 dwFlags
|= REALTIME_PRIORITY_CLASS
;
839 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
840 dwFlags
|= NORMAL_PRIORITY_CLASS
;
844 bool ok
= ::CreateProcess
846 // WinCE requires appname to be non null
847 // Win32 allows for null
849 moduleName
.t_str(), // application name
850 wxMSW_CONV_LPTSTR(arguments
), // arguments
852 NULL
, // application name (use only cmd line)
853 wxMSW_CONV_LPTSTR(command
), // full command line
855 NULL
, // security attributes: defaults for both
856 NULL
, // the process and its main thread
857 redirect
, // inherit handles if we use pipes
858 dwFlags
, // process creation flags
859 envBuffer
.data(), // environment (may be NULL which is fine)
860 useCwd
// initial working directory
861 ? wxMSW_CONV_LPTSTR(env
->cwd
)
862 : NULL
, // (or use the same)
863 &si
, // startup info (unused here)
867 #if wxUSE_STREAMS && !defined(__WXWINCE__)
868 // we can close the pipe ends used by child anyhow
871 ::CloseHandle(pipeIn
.Detach(wxPipe::Read
));
872 ::CloseHandle(pipeOut
.Detach(wxPipe::Write
));
873 ::CloseHandle(pipeErr
.Detach(wxPipe::Write
));
875 #endif // wxUSE_STREAMS
879 #if wxUSE_STREAMS && !defined(__WXWINCE__)
880 // close the other handles too
883 ::CloseHandle(pipeOut
.Detach(wxPipe::Read
));
884 ::CloseHandle(pipeErr
.Detach(wxPipe::Read
));
886 #endif // wxUSE_STREAMS
888 wxLogSysError(_("Execution of command '%s' failed"), command
.c_str());
890 return flags
& wxEXEC_SYNC
? -1 : 0;
893 #if wxUSE_STREAMS && !defined(__WXWINCE__)
894 // the input buffer bufOut is connected to stdout, this is why it is
895 // called bufOut and not bufIn
896 wxStreamTempInputBuffer bufOut
,
901 // We can now initialize the wxStreams
903 outStream
= new wxPipeInputStream(pipeOut
.Detach(wxPipe::Read
));
905 errStream
= new wxPipeInputStream(pipeErr
.Detach(wxPipe::Read
));
907 inStream
= new wxPipeOutputStream(hpipeStdinWrite
);
909 handler
->SetPipeStreams(outStream
, inStream
, errStream
);
911 bufOut
.Init(outStream
);
912 bufErr
.Init(errStream
);
914 #endif // wxUSE_STREAMS
916 // create a hidden window to receive notification about process
918 HWND hwnd
= wxCreateHiddenWindow
920 &gs_classForHiddenWindow
,
921 wxMSWEXEC_WNDCLASSNAME
,
922 (WNDPROC
)wxExecuteWindowCbk
925 wxASSERT_MSG( hwnd
, wxT("can't create a hidden window for wxExecute") );
928 wxExecuteData
*data
= new wxExecuteData
;
929 data
->hProcess
= pi
.hProcess
;
930 data
->dwProcessId
= pi
.dwProcessId
;
932 data
->state
= (flags
& wxEXEC_SYNC
) != 0;
933 if ( flags
& wxEXEC_SYNC
)
935 // handler may be !NULL for capturing program output, but we don't use
936 // it wxExecuteData struct in this case
937 data
->handler
= NULL
;
941 // may be NULL or not
942 data
->handler
= handler
;
945 handler
->SetPid(pi
.dwProcessId
);
949 HANDLE hThread
= ::CreateThread(NULL
,
956 // resume process we created now - whether the thread creation succeeded or
958 if ( ::ResumeThread(pi
.hThread
) == (DWORD
)-1 )
960 // ignore it - what can we do?
961 wxLogLastError(wxT("ResumeThread in wxExecute"));
964 // close unneeded handle
965 if ( !::CloseHandle(pi
.hThread
) )
967 wxLogLastError(wxT("CloseHandle(hThread)"));
972 wxLogLastError(wxT("CreateThread in wxExecute"));
977 // the process still started up successfully...
978 return pi
.dwProcessId
;
981 gs_asyncThreads
.push_back(hThread
);
983 #if wxUSE_IPC && !defined(__WXWINCE__)
984 // second part of DDE hack: now establish the DDE conversation with the
985 // just launched process
986 if ( !ddeServer
.empty() )
990 // give the process the time to init itself
992 // we use a very big timeout hoping that WaitForInputIdle() will return
993 // much sooner, but not INFINITE just in case the process hangs
994 // completely - like this we will regain control sooner or later
995 switch ( ::WaitForInputIdle(pi
.hProcess
, 10000 /* 10 seconds */) )
998 wxFAIL_MSG( wxT("unexpected WaitForInputIdle() return code") );
1002 wxLogLastError(wxT("WaitForInputIdle() in wxExecute"));
1005 wxLogDebug(wxT("Timeout too small in WaitForInputIdle"));
1011 // ok, process ready to accept DDE requests
1012 ddeOK
= wxExecuteDDE(ddeServer
, ddeTopic
, ddeCommand
);
1017 wxLogDebug(wxT("Failed to send DDE request to the process \"%s\"."),
1023 if ( !(flags
& wxEXEC_SYNC
) )
1025 // clean up will be done when the process terminates
1028 return pi
.dwProcessId
;
1031 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
1032 wxCHECK_MSG( traits
, -1, wxT("no wxAppTraits in wxExecute()?") );
1034 void *cookie
= NULL
;
1035 if ( !(flags
& wxEXEC_NODISABLE
) )
1037 // disable all app windows while waiting for the child process to finish
1038 cookie
= traits
->BeforeChildWaitLoop();
1041 // wait until the child process terminates
1042 while ( data
->state
)
1044 #if wxUSE_STREAMS && !defined(__WXWINCE__)
1045 if ( !bufOut
.Update() && !bufErr
.Update() )
1046 #endif // wxUSE_STREAMS
1048 // don't eat 100% of the CPU -- ugly but anything else requires
1049 // real async IO which we don't have for the moment
1053 // we must always process messages for our hidden window or we'd never
1054 // get wxWM_PROC_TERMINATED and so this loop would never terminate
1056 ::PeekMessage(&msg
, data
->hWnd
, 0, 0, PM_REMOVE
);
1058 // we may also need to process messages for all the other application
1060 if ( !(flags
& wxEXEC_NOEVENTS
) )
1062 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
1068 if ( !(flags
& wxEXEC_NODISABLE
) )
1070 // reenable disabled windows back
1071 traits
->AfterChildWaitLoop(cookie
);
1074 DWORD dwExitCode
= data
->dwExitCode
;
1077 // return the exit code
1081 template <typename CharType
>
1082 long wxExecuteImpl(CharType
**argv
, int flags
, wxProcess
*handler
,
1083 const wxExecuteEnv
*env
)
1086 command
.reserve(1024);
1096 // we need to quote empty arguments, otherwise they'd just
1102 // escape any quotes present in the string to avoid interfering
1103 // with the command line parsing in the child process
1104 arg
.Replace("\"", "\\\"", true /* replace all */);
1106 // and quote any arguments containing the spaces to prevent them from
1107 // being broken down
1108 quote
= arg
.find_first_of(" \t") != wxString::npos
;
1112 command
+= '\"' + arg
+ '\"';
1122 return wxExecute(command
, flags
, handler
, env
);
1125 long wxExecute(char **argv
, int flags
, wxProcess
*handler
,
1126 const wxExecuteEnv
*env
)
1128 return wxExecuteImpl(argv
, flags
, handler
, env
);
1133 long wxExecute(wchar_t **argv
, int flags
, wxProcess
*handler
,
1134 const wxExecuteEnv
*env
)
1136 return wxExecuteImpl(argv
, flags
, handler
, env
);
1139 #endif // wxUSE_UNICODE