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 // ----------------------------------------------------------------------------
87 // ----------------------------------------------------------------------------
89 // this message is sent when the process we're waiting for terminates
90 #define wxWM_PROC_TERMINATED (WM_USER + 10000)
92 // ----------------------------------------------------------------------------
93 // this module globals
94 // ----------------------------------------------------------------------------
96 // we need to create a hidden window to receive the process termination
97 // notifications and for this we need a (Win) class name for it which we will
98 // register the first time it's needed
99 static const wxChar
*wxMSWEXEC_WNDCLASSNAME
= wxT("_wxExecute_Internal_Class");
100 static const wxChar
*gs_classForHiddenWindow
= NULL
;
102 // event used to wake up threads waiting in wxExecuteThread
103 static HANDLE gs_heventShutdown
= NULL
;
105 // handles of all threads monitoring the execution of asynchronously running
107 static wxVector
<HANDLE
> gs_asyncThreads
;
109 // ----------------------------------------------------------------------------
111 // ----------------------------------------------------------------------------
113 // structure describing the process we're being waiting for
119 if ( !::CloseHandle(hProcess
) )
121 wxLogLastError(wxT("CloseHandle(hProcess)"));
125 HWND hWnd
; // window to send wxWM_PROC_TERMINATED to
126 HANDLE hProcess
; // handle of the process
127 DWORD dwProcessId
; // pid of the process
129 DWORD dwExitCode
; // the exit code of the process
130 bool state
; // set to false when the process finishes
133 class wxExecuteModule
: public wxModule
136 virtual bool OnInit() { return true; }
137 virtual void OnExit()
139 if ( gs_heventShutdown
)
141 // stop any threads waiting for the termination of asynchronously
143 if ( !::SetEvent(gs_heventShutdown
) )
145 wxLogDebug(wxT("Failed to set shutdown event in wxExecuteModule"));
148 ::CloseHandle(gs_heventShutdown
);
149 gs_heventShutdown
= NULL
;
151 // now wait until they terminate
152 if ( !gs_asyncThreads
.empty() )
154 const size_t numThreads
= gs_asyncThreads
.size();
156 if ( ::WaitForMultipleObjects
160 TRUE
, // wait for all of them to become signalled
161 3000 // long but finite value
164 wxLogDebug(wxT("Failed to stop all wxExecute monitor threads"));
167 for ( size_t n
= 0; n
< numThreads
; n
++ )
169 ::CloseHandle(gs_asyncThreads
[n
]);
172 gs_asyncThreads
.clear();
176 if ( gs_classForHiddenWindow
)
178 if ( !::UnregisterClass(wxMSWEXEC_WNDCLASSNAME
, wxGetInstance()) )
180 wxLogLastError(wxT("UnregisterClass(wxExecClass)"));
183 gs_classForHiddenWindow
= NULL
;
188 DECLARE_DYNAMIC_CLASS(wxExecuteModule
)
191 IMPLEMENT_DYNAMIC_CLASS(wxExecuteModule
, wxModule
)
193 #if wxUSE_STREAMS && !defined(__WXWINCE__)
195 // ----------------------------------------------------------------------------
197 // ----------------------------------------------------------------------------
199 class wxPipeInputStream
: public wxInputStream
202 wxPipeInputStream(HANDLE hInput
);
203 virtual ~wxPipeInputStream();
205 // returns true if the pipe is still opened
206 bool IsOpened() const { return m_hInput
!= INVALID_HANDLE_VALUE
; }
208 // returns true if there is any data to be read from the pipe
209 virtual bool CanRead() const;
212 size_t OnSysRead(void *buffer
, size_t len
);
217 wxDECLARE_NO_COPY_CLASS(wxPipeInputStream
);
220 class wxPipeOutputStream
: public wxOutputStream
223 wxPipeOutputStream(HANDLE hOutput
);
224 virtual ~wxPipeOutputStream() { Close(); }
228 size_t OnSysWrite(const void *buffer
, size_t len
);
233 wxDECLARE_NO_COPY_CLASS(wxPipeOutputStream
);
236 // define this to let wxexec.cpp know that we know what we're doing
237 #define _WX_USED_BY_WXEXECUTE_
238 #include "../common/execcmn.cpp"
240 // ----------------------------------------------------------------------------
241 // wxPipe represents a Win32 anonymous pipe
242 // ----------------------------------------------------------------------------
247 // the symbolic names for the pipe ends
254 // default ctor doesn't do anything
255 wxPipe() { m_handles
[Read
] = m_handles
[Write
] = INVALID_HANDLE_VALUE
; }
257 // create the pipe, return true if ok, false on error
260 // default secutiry attributes
261 SECURITY_ATTRIBUTES security
;
263 security
.nLength
= sizeof(security
);
264 security
.lpSecurityDescriptor
= NULL
;
265 security
.bInheritHandle
= TRUE
; // to pass it to the child
267 if ( !::CreatePipe(&m_handles
[0], &m_handles
[1], &security
, 0) )
269 wxLogSysError(_("Failed to create an anonymous pipe"));
277 // return true if we were created successfully
278 bool IsOk() const { return m_handles
[Read
] != INVALID_HANDLE_VALUE
; }
280 // return the descriptor for one of the pipe ends
281 HANDLE
operator[](Direction which
) const { return m_handles
[which
]; }
283 // detach a descriptor, meaning that the pipe dtor won't close it, and
285 HANDLE
Detach(Direction which
)
287 HANDLE handle
= m_handles
[which
];
288 m_handles
[which
] = INVALID_HANDLE_VALUE
;
293 // close the pipe descriptors
296 for ( size_t n
= 0; n
< WXSIZEOF(m_handles
); n
++ )
298 if ( m_handles
[n
] != INVALID_HANDLE_VALUE
)
300 ::CloseHandle(m_handles
[n
]);
301 m_handles
[n
] = INVALID_HANDLE_VALUE
;
306 // dtor closes the pipe descriptors
307 ~wxPipe() { Close(); }
313 #endif // wxUSE_STREAMS
315 // ============================================================================
317 // ============================================================================
319 // ----------------------------------------------------------------------------
320 // process termination detecting support
321 // ----------------------------------------------------------------------------
323 // thread function for the thread monitoring the process termination
324 static DWORD __stdcall
wxExecuteThread(void *arg
)
326 wxExecuteData
* const data
= (wxExecuteData
*)arg
;
328 // create the shutdown event if we're the first thread starting to wait
329 if ( !gs_heventShutdown
)
331 // create a manual initially non-signalled event object
332 gs_heventShutdown
= ::CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
333 if ( !gs_heventShutdown
)
335 wxLogDebug(wxT("CreateEvent() in wxExecuteThread failed"));
339 HANDLE handles
[2] = { data
->hProcess
, gs_heventShutdown
};
340 switch ( ::WaitForMultipleObjects(2, handles
, FALSE
, INFINITE
) )
343 // process terminated, get its exit code
344 if ( !::GetExitCodeProcess(data
->hProcess
, &data
->dwExitCode
) )
346 wxLogLastError(wxT("GetExitCodeProcess"));
349 wxASSERT_MSG( data
->dwExitCode
!= STILL_ACTIVE
,
350 wxT("process should have terminated") );
352 // send a message indicating process termination to the window
353 ::SendMessage(data
->hWnd
, wxWM_PROC_TERMINATED
, 0, (LPARAM
)data
);
356 case WAIT_OBJECT_0
+ 1:
357 // we're shutting down but the process is still running -- leave it
358 // run but clean up the associated data
363 //else: exiting while synchronously executing process is still
364 // running? this shouldn't happen...
368 wxLogDebug(wxT("Waiting for the process termination failed!"));
374 // window procedure of a hidden window which is created just to receive
375 // the notification message when a process exits
376 LRESULT APIENTRY _EXPORT
wxExecuteWindowCbk(HWND hWnd
, UINT message
,
377 WPARAM wParam
, LPARAM lParam
)
379 if ( message
== wxWM_PROC_TERMINATED
)
381 DestroyWindow(hWnd
); // we don't need it any more
383 wxExecuteData
* const data
= (wxExecuteData
*)lParam
;
386 data
->handler
->OnTerminate((int)data
->dwProcessId
,
387 (int)data
->dwExitCode
);
392 // we're executing synchronously, tell the waiting thread
393 // that the process finished
398 // asynchronous execution - we should do the clean up
406 return ::DefWindowProc(hWnd
, message
, wParam
, lParam
);
410 // ============================================================================
411 // implementation of IO redirection support classes
412 // ============================================================================
414 #if wxUSE_STREAMS && !defined(__WXWINCE__)
416 // ----------------------------------------------------------------------------
417 // wxPipeInputStreams
418 // ----------------------------------------------------------------------------
420 wxPipeInputStream::wxPipeInputStream(HANDLE hInput
)
425 wxPipeInputStream::~wxPipeInputStream()
427 if ( m_hInput
!= INVALID_HANDLE_VALUE
)
428 ::CloseHandle(m_hInput
);
431 bool wxPipeInputStream::CanRead() const
433 // we can read if there's something in the put back buffer
434 // even pipe is closed
435 if ( m_wbacksize
> m_wbackcur
)
438 wxPipeInputStream
* const self
= wxConstCast(this, wxPipeInputStream
);
442 // set back to mark Eof as it may have been unset by Ungetch()
443 self
->m_lasterror
= wxSTREAM_EOF
;
449 // function name is misleading, it works with anon pipes as well
450 DWORD rc
= ::PeekNamedPipe
453 NULL
, 0, // ptr to buffer and its size
454 NULL
, // [out] bytes read
455 &nAvailable
, // [out] bytes available
456 NULL
// [out] bytes left
461 if ( ::GetLastError() != ERROR_BROKEN_PIPE
)
464 wxLogLastError(wxT("PeekNamedPipe"));
467 // don't try to continue reading from a pipe if an error occurred or if
468 // it had been closed
469 ::CloseHandle(m_hInput
);
471 self
->m_hInput
= INVALID_HANDLE_VALUE
;
472 self
->m_lasterror
= wxSTREAM_EOF
;
477 return nAvailable
!= 0;
480 size_t wxPipeInputStream::OnSysRead(void *buffer
, size_t len
)
484 m_lasterror
= wxSTREAM_EOF
;
490 if ( !::ReadFile(m_hInput
, buffer
, len
, &bytesRead
, NULL
) )
492 m_lasterror
= ::GetLastError() == ERROR_BROKEN_PIPE
494 : wxSTREAM_READ_ERROR
;
497 // bytesRead is set to 0, as desired, if an error occurred
501 // ----------------------------------------------------------------------------
502 // wxPipeOutputStream
503 // ----------------------------------------------------------------------------
505 wxPipeOutputStream::wxPipeOutputStream(HANDLE hOutput
)
509 // unblock the pipe to prevent deadlocks when we're writing to the pipe
510 // from which the child process can't read because it is writing in its own
512 DWORD mode
= PIPE_READMODE_BYTE
| PIPE_NOWAIT
;
513 if ( !::SetNamedPipeHandleState
517 NULL
, // collection count (we don't set it)
518 NULL
// timeout (we don't set it neither)
521 wxLogLastError(wxT("SetNamedPipeHandleState(PIPE_NOWAIT)"));
525 bool wxPipeOutputStream::Close()
527 return ::CloseHandle(m_hOutput
) != 0;
531 size_t wxPipeOutputStream::OnSysWrite(const void *buffer
, size_t len
)
533 m_lasterror
= wxSTREAM_NO_ERROR
;
535 DWORD totalWritten
= 0;
539 if ( !::WriteFile(m_hOutput
, buffer
, len
, &chunkWritten
, NULL
) )
541 m_lasterror
= ::GetLastError() == ERROR_BROKEN_PIPE
543 : wxSTREAM_WRITE_ERROR
;
550 buffer
= (char *)buffer
+ chunkWritten
;
551 totalWritten
+= chunkWritten
;
558 #endif // wxUSE_STREAMS
560 // ============================================================================
561 // wxExecute functions family
562 // ============================================================================
566 // connect to the given server via DDE and ask it to execute the command
568 wxExecuteDDE(const wxString
& ddeServer
,
569 const wxString
& ddeTopic
,
570 const wxString
& ddeCommand
)
572 bool ok
wxDUMMY_INITIALIZE(false);
576 conn
= client
.MakeConnection(wxEmptyString
, ddeServer
, ddeTopic
);
581 else // connected to DDE server
583 // the added complication here is that although most programs use
584 // XTYP_EXECUTE for their DDE API, some important ones -- like Word
585 // and other MS stuff - use XTYP_REQUEST!
587 // moreover, anotheri mportant program (IE) understands both but
588 // returns an error from Execute() so we must try Request() first
589 // to avoid doing it twice
591 // we're prepared for this one to fail, so don't show errors
594 ok
= conn
->Request(ddeCommand
) != NULL
;
599 // now try execute -- but show the errors
600 ok
= conn
->Execute(ddeCommand
);
609 long wxExecute(const wxString
& cmd
, int flags
, wxProcess
*handler
,
610 const wxExecuteEnv
*env
)
612 wxCHECK_MSG( !cmd
.empty(), 0, wxT("empty command in wxExecute") );
615 // for many reasons, the code below breaks down if it's called from another
616 // thread -- this could be fixed, but as Unix versions don't support this
617 // neither I don't want to waste time on this now
618 wxASSERT_MSG( wxThread::IsMain(),
619 wxT("wxExecute() can be called only from the main thread") );
620 #endif // wxUSE_THREADS
625 // DDE hack: this is really not pretty, but we need to allow this for
626 // transparent handling of DDE servers in wxMimeTypesManager. Usually it
627 // returns the command which should be run to view/open/... a file of the
628 // given type. Sometimes, however, this command just launches the server
629 // and an additional DDE request must be made to really open the file. To
630 // keep all this well hidden from the application, we allow a special form
631 // of command: WX_DDE#<command>#DDE_SERVER#DDE_TOPIC#DDE_COMMAND in which
632 // case we execute just <command> and process the rest below
633 wxString ddeServer
, ddeTopic
, ddeCommand
;
634 static const size_t lenDdePrefix
= 7; // strlen("WX_DDE:")
635 if ( cmd
.Left(lenDdePrefix
) == wxT("WX_DDE#") )
637 // speed up the concatenations below
638 ddeServer
.reserve(256);
639 ddeTopic
.reserve(256);
640 ddeCommand
.reserve(256);
642 const wxChar
*p
= cmd
.c_str() + 7;
643 while ( *p
&& *p
!= wxT('#') )
655 wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute"));
658 while ( *p
&& *p
!= wxT('#') )
670 wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute"));
673 while ( *p
&& *p
!= wxT('#') )
685 wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute"));
693 // if we want to just launch the program and not wait for its
694 // termination, try to execute DDE command right now, it can succeed if
695 // the process is already running - but as it fails if it's not
696 // running, suppress any errors it might generate
697 if ( !(flags
& wxEXEC_SYNC
) )
700 if ( wxExecuteDDE(ddeServer
, ddeTopic
, ddeCommand
) )
702 // a dummy PID - this is a hack, of course, but it's well worth
703 // it as we don't open a new server each time we're called
704 // which would be quite bad
716 // the IO redirection is only supported with wxUSE_STREAMS
717 BOOL redirect
= FALSE
;
719 #if wxUSE_STREAMS && !defined(__WXWINCE__)
720 wxPipe pipeIn
, pipeOut
, pipeErr
;
722 // we'll save here the copy of pipeIn[Write]
723 HANDLE hpipeStdinWrite
= INVALID_HANDLE_VALUE
;
725 // open the pipes to which child process IO will be redirected if needed
726 if ( handler
&& handler
->IsRedirected() )
728 // create pipes for redirecting stdin, stdout and stderr
729 if ( !pipeIn
.Create() || !pipeOut
.Create() || !pipeErr
.Create() )
731 wxLogSysError(_("Failed to redirect the child process IO"));
733 // indicate failure: we need to return different error code
734 // depending on the sync flag
735 return flags
& wxEXEC_SYNC
? -1 : 0;
740 #endif // wxUSE_STREAMS
742 // create the process
747 #if wxUSE_STREAMS && !defined(__WXWINCE__)
750 si
.dwFlags
= STARTF_USESTDHANDLES
;
752 si
.hStdInput
= pipeIn
[wxPipe::Read
];
753 si
.hStdOutput
= pipeOut
[wxPipe::Write
];
754 si
.hStdError
= pipeErr
[wxPipe::Write
];
756 // we must duplicate the handle to the write side of stdin pipe to make
757 // it non inheritable: indeed, we must close the writing end of pipeIn
758 // before launching the child process as otherwise this handle will be
759 // inherited by the child which will never close it and so the pipe
760 // will never be closed and the child will be left stuck in ReadFile()
761 HANDLE pipeInWrite
= pipeIn
.Detach(wxPipe::Write
);
762 if ( !::DuplicateHandle
764 ::GetCurrentProcess(),
766 ::GetCurrentProcess(),
768 0, // desired access: unused here
769 FALSE
, // not inherited
770 DUPLICATE_SAME_ACCESS
// same access as for src handle
773 wxLogLastError(wxT("DuplicateHandle"));
776 ::CloseHandle(pipeInWrite
);
778 #endif // wxUSE_STREAMS
780 // The default logic for showing the console is to show it only if the IO
781 // is not redirected however wxEXEC_{SHOW,HIDE}_CONSOLE flags can be
782 // explicitly specified to change it.
783 if ( (flags
& wxEXEC_HIDE_CONSOLE
) ||
784 (redirect
&& !(flags
& wxEXEC_SHOW_CONSOLE
)) )
786 si
.dwFlags
|= STARTF_USESHOWWINDOW
;
787 si
.wShowWindow
= SW_HIDE
;
791 PROCESS_INFORMATION pi
;
792 DWORD dwFlags
= CREATE_SUSPENDED
;
795 if ( (flags
& wxEXEC_MAKE_GROUP_LEADER
) &&
796 (wxGetOsVersion() == wxOS_WINDOWS_NT
) )
797 dwFlags
|= CREATE_NEW_PROCESS_GROUP
;
799 dwFlags
|= CREATE_DEFAULT_ERROR_MODE
;
801 // we are assuming commands without spaces for now
802 wxString moduleName
= command
.BeforeFirst(wxT(' '));
803 wxString arguments
= command
.AfterFirst(wxT(' '));
806 wxWxCharBuffer envBuffer
;
810 useCwd
= !env
->cwd
.empty();
812 // Translate environment variable map into NUL-terminated list of
813 // NUL-terminated strings.
814 if ( !env
->env
.empty() )
817 // Environment variables can contain non-ASCII characters. We could
818 // check for it and not use this flag if everything is really ASCII
819 // only but there doesn't seem to be any reason to do it so just
820 // assume Unicode by default.
821 dwFlags
|= CREATE_UNICODE_ENVIRONMENT
;
822 #endif // wxUSE_UNICODE
824 wxEnvVariableHashMap::const_iterator it
;
826 size_t envSz
= 1; // ending '\0'
827 for ( it
= env
->env
.begin(); it
!= env
->env
.end(); ++it
)
829 // Add size of env variable name and value, and '=' char and
831 envSz
+= it
->first
.length() + it
->second
.length() + 2;
834 envBuffer
.extend(envSz
);
836 wxChar
*p
= envBuffer
.data();
837 for ( it
= env
->env
.begin(); it
!= env
->env
.end(); ++it
)
839 const wxString line
= it
->first
+ wxS("=") + it
->second
;
841 // Include the trailing NUL which will always terminate the
842 // buffer returned by t_str().
843 const size_t len
= line
.length() + 1;
845 wxTmemcpy(p
, line
.t_str(), len
);
850 // And another NUL to terminate the list of NUL-terminated strings.
855 bool ok
= ::CreateProcess
857 // WinCE requires appname to be non null
858 // Win32 allows for null
860 static_cast<const TCHAR
*>(
861 moduleName
.t_str()),// application name
862 const_cast<TCHAR
*>(static_cast<const TCHAR
*>(
863 arguments
.t_str())), // arguments
865 NULL
, // application name (use only cmd line)
866 const_cast<TCHAR
*>(static_cast<const TCHAR
*>(
867 command
.t_str())), // full command line
869 NULL
, // security attributes: defaults for both
870 NULL
, // the process and its main thread
871 redirect
, // inherit handles if we use pipes
872 dwFlags
, // process creation flags
873 envBuffer
.data(), // environment (may be NULL which is fine)
874 useCwd
// initial working directory
875 ? const_cast<TCHAR
*>(static_cast<const TCHAR
*>(env
->cwd
.t_str()))
876 : NULL
, // (or use the same)
877 &si
, // startup info (unused here)
881 #if wxUSE_STREAMS && !defined(__WXWINCE__)
882 // we can close the pipe ends used by child anyhow
885 ::CloseHandle(pipeIn
.Detach(wxPipe::Read
));
886 ::CloseHandle(pipeOut
.Detach(wxPipe::Write
));
887 ::CloseHandle(pipeErr
.Detach(wxPipe::Write
));
889 #endif // wxUSE_STREAMS
893 #if wxUSE_STREAMS && !defined(__WXWINCE__)
894 // close the other handles too
897 ::CloseHandle(pipeOut
.Detach(wxPipe::Read
));
898 ::CloseHandle(pipeErr
.Detach(wxPipe::Read
));
900 #endif // wxUSE_STREAMS
902 wxLogSysError(_("Execution of command '%s' failed"), command
.c_str());
904 return flags
& wxEXEC_SYNC
? -1 : 0;
907 #if wxUSE_STREAMS && !defined(__WXWINCE__)
908 // the input buffer bufOut is connected to stdout, this is why it is
909 // called bufOut and not bufIn
910 wxStreamTempInputBuffer bufOut
,
915 // We can now initialize the wxStreams
917 outStream
= new wxPipeInputStream(pipeOut
.Detach(wxPipe::Read
));
919 errStream
= new wxPipeInputStream(pipeErr
.Detach(wxPipe::Read
));
921 inStream
= new wxPipeOutputStream(hpipeStdinWrite
);
923 handler
->SetPipeStreams(outStream
, inStream
, errStream
);
925 bufOut
.Init(outStream
);
926 bufErr
.Init(errStream
);
928 #endif // wxUSE_STREAMS
930 // create a hidden window to receive notification about process
932 HWND hwnd
= wxCreateHiddenWindow
934 &gs_classForHiddenWindow
,
935 wxMSWEXEC_WNDCLASSNAME
,
936 (WNDPROC
)wxExecuteWindowCbk
939 wxASSERT_MSG( hwnd
, wxT("can't create a hidden window for wxExecute") );
942 wxExecuteData
*data
= new wxExecuteData
;
943 data
->hProcess
= pi
.hProcess
;
944 data
->dwProcessId
= pi
.dwProcessId
;
946 data
->state
= (flags
& wxEXEC_SYNC
) != 0;
947 if ( flags
& wxEXEC_SYNC
)
949 // handler may be !NULL for capturing program output, but we don't use
950 // it wxExecuteData struct in this case
951 data
->handler
= NULL
;
955 // may be NULL or not
956 data
->handler
= handler
;
959 handler
->SetPid(pi
.dwProcessId
);
963 HANDLE hThread
= ::CreateThread(NULL
,
970 // resume process we created now - whether the thread creation succeeded or
972 if ( ::ResumeThread(pi
.hThread
) == (DWORD
)-1 )
974 // ignore it - what can we do?
975 wxLogLastError(wxT("ResumeThread in wxExecute"));
978 // close unneeded handle
979 if ( !::CloseHandle(pi
.hThread
) )
981 wxLogLastError(wxT("CloseHandle(hThread)"));
986 wxLogLastError(wxT("CreateThread in wxExecute"));
991 // the process still started up successfully...
992 return pi
.dwProcessId
;
995 gs_asyncThreads
.push_back(hThread
);
997 #if wxUSE_IPC && !defined(__WXWINCE__)
998 // second part of DDE hack: now establish the DDE conversation with the
999 // just launched process
1000 if ( !ddeServer
.empty() )
1004 // give the process the time to init itself
1006 // we use a very big timeout hoping that WaitForInputIdle() will return
1007 // much sooner, but not INFINITE just in case the process hangs
1008 // completely - like this we will regain control sooner or later
1009 switch ( ::WaitForInputIdle(pi
.hProcess
, 10000 /* 10 seconds */) )
1012 wxFAIL_MSG( wxT("unexpected WaitForInputIdle() return code") );
1016 wxLogLastError(wxT("WaitForInputIdle() in wxExecute"));
1019 wxLogDebug(wxT("Timeout too small in WaitForInputIdle"));
1025 // ok, process ready to accept DDE requests
1026 ok
= wxExecuteDDE(ddeServer
, ddeTopic
, ddeCommand
);
1031 wxLogDebug(wxT("Failed to send DDE request to the process \"%s\"."),
1037 if ( !(flags
& wxEXEC_SYNC
) )
1039 // clean up will be done when the process terminates
1042 return pi
.dwProcessId
;
1045 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
1046 wxCHECK_MSG( traits
, -1, wxT("no wxAppTraits in wxExecute()?") );
1048 void *cookie
= NULL
;
1049 if ( !(flags
& wxEXEC_NODISABLE
) )
1051 // disable all app windows while waiting for the child process to finish
1052 cookie
= traits
->BeforeChildWaitLoop();
1055 // wait until the child process terminates
1056 while ( data
->state
)
1058 #if wxUSE_STREAMS && !defined(__WXWINCE__)
1059 if ( !bufOut
.Update() && !bufErr
.Update() )
1060 #endif // wxUSE_STREAMS
1062 // don't eat 100% of the CPU -- ugly but anything else requires
1063 // real async IO which we don't have for the moment
1067 // we must always process messages for our hidden window or we'd never
1068 // get wxWM_PROC_TERMINATED and so this loop would never terminate
1070 ::PeekMessage(&msg
, data
->hWnd
, 0, 0, PM_REMOVE
);
1072 // we may also need to process messages for all the other application
1074 if ( !(flags
& wxEXEC_NOEVENTS
) )
1076 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
1082 if ( !(flags
& wxEXEC_NODISABLE
) )
1084 // reenable disabled windows back
1085 traits
->AfterChildWaitLoop(cookie
);
1088 DWORD dwExitCode
= data
->dwExitCode
;
1091 // return the exit code
1095 template <typename CharType
>
1096 long wxExecuteImpl(CharType
**argv
, int flags
, wxProcess
*handler
,
1097 const wxExecuteEnv
*env
)
1100 command
.reserve(1024);
1110 // we need to quote empty arguments, otherwise they'd just
1116 // escape any quotes present in the string to avoid interfering
1117 // with the command line parsing in the child process
1118 arg
.Replace("\"", "\\\"", true /* replace all */);
1120 // and quote any arguments containing the spaces to prevent them from
1121 // being broken down
1122 quote
= arg
.find_first_of(" \t") != wxString::npos
;
1126 command
+= '\"' + arg
+ '\"';
1136 return wxExecute(command
, flags
, handler
, env
);
1139 long wxExecute(char **argv
, int flags
, wxProcess
*handler
,
1140 const wxExecuteEnv
*env
)
1142 return wxExecuteImpl(argv
, flags
, handler
, env
);
1147 long wxExecute(wchar_t **argv
, int flags
, wxProcess
*handler
,
1148 const wxExecuteEnv
*env
)
1150 return wxExecuteImpl(argv
, flags
, handler
, env
);
1153 #endif // wxUSE_UNICODE