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"
206 // define this to let wxexec.cpp know that we know what we're doing
207 #define _WX_USED_BY_WXEXECUTE_
208 #include "../common/execcmn.cpp"
210 // ----------------------------------------------------------------------------
211 // wxPipe represents a Win32 anonymous pipe
212 // ----------------------------------------------------------------------------
217 // the symbolic names for the pipe ends
224 // default ctor doesn't do anything
225 wxPipe() { m_handles
[Read
] = m_handles
[Write
] = INVALID_HANDLE_VALUE
; }
227 // create the pipe, return true if ok, false on error
230 // default secutiry attributes
231 SECURITY_ATTRIBUTES security
;
233 security
.nLength
= sizeof(security
);
234 security
.lpSecurityDescriptor
= NULL
;
235 security
.bInheritHandle
= TRUE
; // to pass it to the child
237 if ( !::CreatePipe(&m_handles
[0], &m_handles
[1], &security
, 0) )
239 wxLogSysError(_("Failed to create an anonymous pipe"));
247 // return true if we were created successfully
248 bool IsOk() const { return m_handles
[Read
] != INVALID_HANDLE_VALUE
; }
250 // return the descriptor for one of the pipe ends
251 HANDLE
operator[](Direction which
) const { return m_handles
[which
]; }
253 // detach a descriptor, meaning that the pipe dtor won't close it, and
255 HANDLE
Detach(Direction which
)
257 HANDLE handle
= m_handles
[which
];
258 m_handles
[which
] = INVALID_HANDLE_VALUE
;
263 // close the pipe descriptors
266 for ( size_t n
= 0; n
< WXSIZEOF(m_handles
); n
++ )
268 if ( m_handles
[n
] != INVALID_HANDLE_VALUE
)
270 ::CloseHandle(m_handles
[n
]);
271 m_handles
[n
] = INVALID_HANDLE_VALUE
;
276 // dtor closes the pipe descriptors
277 ~wxPipe() { Close(); }
283 #endif // wxUSE_STREAMS
285 // ============================================================================
287 // ============================================================================
289 // ----------------------------------------------------------------------------
290 // process termination detecting support
291 // ----------------------------------------------------------------------------
293 // thread function for the thread monitoring the process termination
294 static DWORD __stdcall
wxExecuteThread(void *arg
)
296 wxExecuteData
* const data
= (wxExecuteData
*)arg
;
298 // create the shutdown event if we're the first thread starting to wait
299 if ( !gs_heventShutdown
)
301 // create a manual initially non-signalled event object
302 gs_heventShutdown
= ::CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
303 if ( !gs_heventShutdown
)
305 wxLogDebug(wxT("CreateEvent() in wxExecuteThread failed"));
309 HANDLE handles
[2] = { data
->hProcess
, gs_heventShutdown
};
310 switch ( ::WaitForMultipleObjects(2, handles
, FALSE
, INFINITE
) )
313 // process terminated, get its exit code
314 if ( !::GetExitCodeProcess(data
->hProcess
, &data
->dwExitCode
) )
316 wxLogLastError(wxT("GetExitCodeProcess"));
319 wxASSERT_MSG( data
->dwExitCode
!= STILL_ACTIVE
,
320 wxT("process should have terminated") );
322 // send a message indicating process termination to the window
323 ::SendMessage(data
->hWnd
, wxWM_PROC_TERMINATED
, 0, (LPARAM
)data
);
326 case WAIT_OBJECT_0
+ 1:
327 // we're shutting down but the process is still running -- leave it
328 // run but clean up the associated data
333 //else: exiting while synchronously executing process is still
334 // running? this shouldn't happen...
338 wxLogDebug(wxT("Waiting for the process termination failed!"));
344 // window procedure of a hidden window which is created just to receive
345 // the notification message when a process exits
346 LRESULT APIENTRY _EXPORT
wxExecuteWindowCbk(HWND hWnd
, UINT message
,
347 WPARAM wParam
, LPARAM lParam
)
349 if ( message
== wxWM_PROC_TERMINATED
)
351 DestroyWindow(hWnd
); // we don't need it any more
353 wxExecuteData
* const data
= (wxExecuteData
*)lParam
;
356 data
->handler
->OnTerminate((int)data
->dwProcessId
,
357 (int)data
->dwExitCode
);
362 // we're executing synchronously, tell the waiting thread
363 // that the process finished
368 // asynchronous execution - we should do the clean up
376 return ::DefWindowProc(hWnd
, message
, wParam
, lParam
);
380 // ============================================================================
381 // implementation of IO redirection support classes
382 // ============================================================================
384 #if wxUSE_STREAMS && !defined(__WXWINCE__)
386 // ----------------------------------------------------------------------------
387 // wxPipeInputStreams
388 // ----------------------------------------------------------------------------
390 wxPipeInputStream::wxPipeInputStream(HANDLE hInput
)
395 wxPipeInputStream::~wxPipeInputStream()
397 if ( m_hInput
!= INVALID_HANDLE_VALUE
)
398 ::CloseHandle(m_hInput
);
401 bool wxPipeInputStream::CanRead() const
403 // we can read if there's something in the put back buffer
404 // even pipe is closed
405 if ( m_wbacksize
> m_wbackcur
)
408 wxPipeInputStream
* const self
= wxConstCast(this, wxPipeInputStream
);
412 // set back to mark Eof as it may have been unset by Ungetch()
413 self
->m_lasterror
= wxSTREAM_EOF
;
419 // function name is misleading, it works with anon pipes as well
420 DWORD rc
= ::PeekNamedPipe
423 NULL
, 0, // ptr to buffer and its size
424 NULL
, // [out] bytes read
425 &nAvailable
, // [out] bytes available
426 NULL
// [out] bytes left
431 if ( ::GetLastError() != ERROR_BROKEN_PIPE
)
434 wxLogLastError(wxT("PeekNamedPipe"));
437 // don't try to continue reading from a pipe if an error occurred or if
438 // it had been closed
439 ::CloseHandle(m_hInput
);
441 self
->m_hInput
= INVALID_HANDLE_VALUE
;
442 self
->m_lasterror
= wxSTREAM_EOF
;
447 return nAvailable
!= 0;
450 size_t wxPipeInputStream::OnSysRead(void *buffer
, size_t len
)
454 m_lasterror
= wxSTREAM_EOF
;
460 if ( !::ReadFile(m_hInput
, buffer
, len
, &bytesRead
, NULL
) )
462 m_lasterror
= ::GetLastError() == ERROR_BROKEN_PIPE
464 : wxSTREAM_READ_ERROR
;
467 // bytesRead is set to 0, as desired, if an error occurred
471 // ----------------------------------------------------------------------------
472 // wxPipeOutputStream
473 // ----------------------------------------------------------------------------
475 wxPipeOutputStream::wxPipeOutputStream(HANDLE hOutput
)
479 // unblock the pipe to prevent deadlocks when we're writing to the pipe
480 // from which the child process can't read because it is writing in its own
482 DWORD mode
= PIPE_READMODE_BYTE
| PIPE_NOWAIT
;
483 if ( !::SetNamedPipeHandleState
487 NULL
, // collection count (we don't set it)
488 NULL
// timeout (we don't set it neither)
491 wxLogLastError(wxT("SetNamedPipeHandleState(PIPE_NOWAIT)"));
495 bool wxPipeOutputStream::Close()
497 return ::CloseHandle(m_hOutput
) != 0;
501 size_t wxPipeOutputStream::OnSysWrite(const void *buffer
, size_t len
)
503 m_lasterror
= wxSTREAM_NO_ERROR
;
505 DWORD totalWritten
= 0;
509 if ( !::WriteFile(m_hOutput
, buffer
, len
, &chunkWritten
, NULL
) )
511 m_lasterror
= ::GetLastError() == ERROR_BROKEN_PIPE
513 : wxSTREAM_WRITE_ERROR
;
520 buffer
= (char *)buffer
+ chunkWritten
;
521 totalWritten
+= chunkWritten
;
528 #endif // wxUSE_STREAMS
530 // ============================================================================
531 // wxExecute functions family
532 // ============================================================================
536 // connect to the given server via DDE and ask it to execute the command
538 wxExecuteDDE(const wxString
& ddeServer
,
539 const wxString
& ddeTopic
,
540 const wxString
& ddeCommand
)
542 bool ok
wxDUMMY_INITIALIZE(false);
546 conn
= client
.MakeConnection(wxEmptyString
, ddeServer
, ddeTopic
);
551 else // connected to DDE server
553 // the added complication here is that although most programs use
554 // XTYP_EXECUTE for their DDE API, some important ones -- like Word
555 // and other MS stuff - use XTYP_REQUEST!
557 // moreover, anotheri mportant program (IE) understands both but
558 // returns an error from Execute() so we must try Request() first
559 // to avoid doing it twice
561 // we're prepared for this one to fail, so don't show errors
564 ok
= conn
->Request(ddeCommand
) != NULL
;
569 // now try execute -- but show the errors
570 ok
= conn
->Execute(ddeCommand
);
579 long wxExecute(const wxString
& cmd
, int flags
, wxProcess
*handler
,
580 const wxExecuteEnv
*env
)
582 wxCHECK_MSG( !cmd
.empty(), 0, wxT("empty command in wxExecute") );
585 // for many reasons, the code below breaks down if it's called from another
586 // thread -- this could be fixed, but as Unix versions don't support this
587 // neither I don't want to waste time on this now
588 wxASSERT_MSG( wxThread::IsMain(),
589 wxT("wxExecute() can be called only from the main thread") );
590 #endif // wxUSE_THREADS
595 // DDE hack: this is really not pretty, but we need to allow this for
596 // transparent handling of DDE servers in wxMimeTypesManager. Usually it
597 // returns the command which should be run to view/open/... a file of the
598 // given type. Sometimes, however, this command just launches the server
599 // and an additional DDE request must be made to really open the file. To
600 // keep all this well hidden from the application, we allow a special form
601 // of command: WX_DDE#<command>#DDE_SERVER#DDE_TOPIC#DDE_COMMAND in which
602 // case we execute just <command> and process the rest below
603 wxString ddeServer
, ddeTopic
, ddeCommand
;
604 static const size_t lenDdePrefix
= 7; // strlen("WX_DDE:")
605 if ( cmd
.Left(lenDdePrefix
) == wxT("WX_DDE#") )
607 // speed up the concatenations below
608 ddeServer
.reserve(256);
609 ddeTopic
.reserve(256);
610 ddeCommand
.reserve(256);
612 const wxChar
*p
= cmd
.c_str() + 7;
613 while ( *p
&& *p
!= wxT('#') )
625 wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute"));
628 while ( *p
&& *p
!= wxT('#') )
640 wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute"));
643 while ( *p
&& *p
!= wxT('#') )
655 wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute"));
663 // if we want to just launch the program and not wait for its
664 // termination, try to execute DDE command right now, it can succeed if
665 // the process is already running - but as it fails if it's not
666 // running, suppress any errors it might generate
667 if ( !(flags
& wxEXEC_SYNC
) )
670 if ( wxExecuteDDE(ddeServer
, ddeTopic
, ddeCommand
) )
672 // a dummy PID - this is a hack, of course, but it's well worth
673 // it as we don't open a new server each time we're called
674 // which would be quite bad
686 // the IO redirection is only supported with wxUSE_STREAMS
687 BOOL redirect
= FALSE
;
689 #if wxUSE_STREAMS && !defined(__WXWINCE__)
690 wxPipe pipeIn
, pipeOut
, pipeErr
;
692 // we'll save here the copy of pipeIn[Write]
693 HANDLE hpipeStdinWrite
= INVALID_HANDLE_VALUE
;
695 // open the pipes to which child process IO will be redirected if needed
696 if ( handler
&& handler
->IsRedirected() )
698 // create pipes for redirecting stdin, stdout and stderr
699 if ( !pipeIn
.Create() || !pipeOut
.Create() || !pipeErr
.Create() )
701 wxLogSysError(_("Failed to redirect the child process IO"));
703 // indicate failure: we need to return different error code
704 // depending on the sync flag
705 return flags
& wxEXEC_SYNC
? -1 : 0;
710 #endif // wxUSE_STREAMS
712 // create the process
717 #if wxUSE_STREAMS && !defined(__WXWINCE__)
720 si
.dwFlags
= STARTF_USESTDHANDLES
;
722 si
.hStdInput
= pipeIn
[wxPipe::Read
];
723 si
.hStdOutput
= pipeOut
[wxPipe::Write
];
724 si
.hStdError
= pipeErr
[wxPipe::Write
];
726 // we must duplicate the handle to the write side of stdin pipe to make
727 // it non inheritable: indeed, we must close the writing end of pipeIn
728 // before launching the child process as otherwise this handle will be
729 // inherited by the child which will never close it and so the pipe
730 // will never be closed and the child will be left stuck in ReadFile()
731 HANDLE pipeInWrite
= pipeIn
.Detach(wxPipe::Write
);
732 if ( !::DuplicateHandle
734 ::GetCurrentProcess(),
736 ::GetCurrentProcess(),
738 0, // desired access: unused here
739 FALSE
, // not inherited
740 DUPLICATE_SAME_ACCESS
// same access as for src handle
743 wxLogLastError(wxT("DuplicateHandle"));
746 ::CloseHandle(pipeInWrite
);
748 #endif // wxUSE_STREAMS
750 // The default logic for showing the console is to show it only if the IO
751 // is not redirected however wxEXEC_{SHOW,HIDE}_CONSOLE flags can be
752 // explicitly specified to change it.
753 if ( (flags
& wxEXEC_HIDE_CONSOLE
) ||
754 (redirect
&& !(flags
& wxEXEC_SHOW_CONSOLE
)) )
756 si
.dwFlags
|= STARTF_USESHOWWINDOW
;
757 si
.wShowWindow
= SW_HIDE
;
761 PROCESS_INFORMATION pi
;
762 DWORD dwFlags
= CREATE_SUSPENDED
;
765 if ( (flags
& wxEXEC_MAKE_GROUP_LEADER
) &&
766 (wxGetOsVersion() == wxOS_WINDOWS_NT
) )
767 dwFlags
|= CREATE_NEW_PROCESS_GROUP
;
769 dwFlags
|= CREATE_DEFAULT_ERROR_MODE
;
771 // we are assuming commands without spaces for now
772 wxString moduleName
= command
.BeforeFirst(wxT(' '));
773 wxString arguments
= command
.AfterFirst(wxT(' '));
776 wxWxCharBuffer envBuffer
;
780 useCwd
= !env
->cwd
.empty();
782 // Translate environment variable map into NUL-terminated list of
783 // NUL-terminated strings.
784 if ( !env
->env
.empty() )
787 // Environment variables can contain non-ASCII characters. We could
788 // check for it and not use this flag if everything is really ASCII
789 // only but there doesn't seem to be any reason to do it so just
790 // assume Unicode by default.
791 dwFlags
|= CREATE_UNICODE_ENVIRONMENT
;
792 #endif // wxUSE_UNICODE
794 wxEnvVariableHashMap::const_iterator it
;
796 size_t envSz
= 1; // ending '\0'
797 for ( it
= env
->env
.begin(); it
!= env
->env
.end(); ++it
)
799 // Add size of env variable name and value, and '=' char and
801 envSz
+= it
->first
.length() + it
->second
.length() + 2;
804 envBuffer
.extend(envSz
);
806 wxChar
*p
= envBuffer
.data();
807 for ( it
= env
->env
.begin(); it
!= env
->env
.end(); ++it
)
809 const wxString line
= it
->first
+ wxS("=") + it
->second
;
811 // Include the trailing NUL which will always terminate the
812 // buffer returned by t_str().
813 const size_t len
= line
.length() + 1;
815 wxTmemcpy(p
, line
.t_str(), len
);
820 // And another NUL to terminate the list of NUL-terminated strings.
825 // Translate wxWidgets priority to Windows conventions.
828 unsigned prio
= handler
->GetPriority();
830 dwFlags
|= IDLE_PRIORITY_CLASS
;
831 else if ( prio
<= 40 )
832 dwFlags
|= BELOW_NORMAL_PRIORITY_CLASS
;
833 else if ( prio
<= 60 )
834 dwFlags
|= NORMAL_PRIORITY_CLASS
;
835 else if ( prio
<= 80 )
836 dwFlags
|= ABOVE_NORMAL_PRIORITY_CLASS
;
837 else if ( prio
<= 99 )
838 dwFlags
|= HIGH_PRIORITY_CLASS
;
839 else if ( prio
<= 100 )
840 dwFlags
|= REALTIME_PRIORITY_CLASS
;
843 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
844 dwFlags
|= NORMAL_PRIORITY_CLASS
;
848 bool ok
= ::CreateProcess
850 // WinCE requires appname to be non null
851 // Win32 allows for null
853 moduleName
.t_str(), // application name
854 wxMSW_CONV_LPTSTR(arguments
), // arguments
856 NULL
, // application name (use only cmd line)
857 wxMSW_CONV_LPTSTR(command
), // full command line
859 NULL
, // security attributes: defaults for both
860 NULL
, // the process and its main thread
861 redirect
, // inherit handles if we use pipes
862 dwFlags
, // process creation flags
863 envBuffer
.data(), // environment (may be NULL which is fine)
864 useCwd
// initial working directory
865 ? wxMSW_CONV_LPTSTR(env
->cwd
)
866 : NULL
, // (or use the same)
867 &si
, // startup info (unused here)
871 #if wxUSE_STREAMS && !defined(__WXWINCE__)
872 // we can close the pipe ends used by child anyhow
875 ::CloseHandle(pipeIn
.Detach(wxPipe::Read
));
876 ::CloseHandle(pipeOut
.Detach(wxPipe::Write
));
877 ::CloseHandle(pipeErr
.Detach(wxPipe::Write
));
879 #endif // wxUSE_STREAMS
883 #if wxUSE_STREAMS && !defined(__WXWINCE__)
884 // close the other handles too
887 ::CloseHandle(pipeOut
.Detach(wxPipe::Read
));
888 ::CloseHandle(pipeErr
.Detach(wxPipe::Read
));
890 #endif // wxUSE_STREAMS
892 wxLogSysError(_("Execution of command '%s' failed"), command
.c_str());
894 return flags
& wxEXEC_SYNC
? -1 : 0;
897 #if wxUSE_STREAMS && !defined(__WXWINCE__)
898 // the input buffer bufOut is connected to stdout, this is why it is
899 // called bufOut and not bufIn
900 wxStreamTempInputBuffer bufOut
,
905 // We can now initialize the wxStreams
907 outStream
= new wxPipeInputStream(pipeOut
.Detach(wxPipe::Read
));
909 errStream
= new wxPipeInputStream(pipeErr
.Detach(wxPipe::Read
));
911 inStream
= new wxPipeOutputStream(hpipeStdinWrite
);
913 handler
->SetPipeStreams(outStream
, inStream
, errStream
);
915 bufOut
.Init(outStream
);
916 bufErr
.Init(errStream
);
918 #endif // wxUSE_STREAMS
920 // create a hidden window to receive notification about process
922 HWND hwnd
= wxCreateHiddenWindow
924 &gs_classForHiddenWindow
,
925 wxMSWEXEC_WNDCLASSNAME
,
926 (WNDPROC
)wxExecuteWindowCbk
929 wxASSERT_MSG( hwnd
, wxT("can't create a hidden window for wxExecute") );
932 wxExecuteData
*data
= new wxExecuteData
;
933 data
->hProcess
= pi
.hProcess
;
934 data
->dwProcessId
= pi
.dwProcessId
;
936 data
->state
= (flags
& wxEXEC_SYNC
) != 0;
937 if ( flags
& wxEXEC_SYNC
)
939 // handler may be !NULL for capturing program output, but we don't use
940 // it wxExecuteData struct in this case
941 data
->handler
= NULL
;
945 // may be NULL or not
946 data
->handler
= handler
;
949 handler
->SetPid(pi
.dwProcessId
);
953 HANDLE hThread
= ::CreateThread(NULL
,
960 // resume process we created now - whether the thread creation succeeded or
962 if ( ::ResumeThread(pi
.hThread
) == (DWORD
)-1 )
964 // ignore it - what can we do?
965 wxLogLastError(wxT("ResumeThread in wxExecute"));
968 // close unneeded handle
969 if ( !::CloseHandle(pi
.hThread
) )
971 wxLogLastError(wxT("CloseHandle(hThread)"));
976 wxLogLastError(wxT("CreateThread in wxExecute"));
981 // the process still started up successfully...
982 return pi
.dwProcessId
;
985 gs_asyncThreads
.push_back(hThread
);
987 #if wxUSE_IPC && !defined(__WXWINCE__)
988 // second part of DDE hack: now establish the DDE conversation with the
989 // just launched process
990 if ( !ddeServer
.empty() )
994 // give the process the time to init itself
996 // we use a very big timeout hoping that WaitForInputIdle() will return
997 // much sooner, but not INFINITE just in case the process hangs
998 // completely - like this we will regain control sooner or later
999 switch ( ::WaitForInputIdle(pi
.hProcess
, 10000 /* 10 seconds */) )
1002 wxFAIL_MSG( wxT("unexpected WaitForInputIdle() return code") );
1006 wxLogLastError(wxT("WaitForInputIdle() in wxExecute"));
1009 wxLogDebug(wxT("Timeout too small in WaitForInputIdle"));
1015 // ok, process ready to accept DDE requests
1016 ddeOK
= wxExecuteDDE(ddeServer
, ddeTopic
, ddeCommand
);
1021 wxLogDebug(wxT("Failed to send DDE request to the process \"%s\"."),
1027 if ( !(flags
& wxEXEC_SYNC
) )
1029 // clean up will be done when the process terminates
1032 return pi
.dwProcessId
;
1035 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
1036 wxCHECK_MSG( traits
, -1, wxT("no wxAppTraits in wxExecute()?") );
1038 void *cookie
= NULL
;
1039 if ( !(flags
& wxEXEC_NODISABLE
) )
1041 // disable all app windows while waiting for the child process to finish
1042 cookie
= traits
->BeforeChildWaitLoop();
1045 // wait until the child process terminates
1046 while ( data
->state
)
1048 #if wxUSE_STREAMS && !defined(__WXWINCE__)
1049 if ( !bufOut
.Update() && !bufErr
.Update() )
1050 #endif // wxUSE_STREAMS
1052 // don't eat 100% of the CPU -- ugly but anything else requires
1053 // real async IO which we don't have for the moment
1057 // we must always process messages for our hidden window or we'd never
1058 // get wxWM_PROC_TERMINATED and so this loop would never terminate
1060 ::PeekMessage(&msg
, data
->hWnd
, 0, 0, PM_REMOVE
);
1062 // we may also need to process messages for all the other application
1064 if ( !(flags
& wxEXEC_NOEVENTS
) )
1066 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
1072 if ( !(flags
& wxEXEC_NODISABLE
) )
1074 // reenable disabled windows back
1075 traits
->AfterChildWaitLoop(cookie
);
1078 DWORD dwExitCode
= data
->dwExitCode
;
1081 // return the exit code
1085 template <typename CharType
>
1086 long wxExecuteImpl(CharType
**argv
, int flags
, wxProcess
*handler
,
1087 const wxExecuteEnv
*env
)
1090 command
.reserve(1024);
1100 // we need to quote empty arguments, otherwise they'd just
1106 // escape any quotes present in the string to avoid interfering
1107 // with the command line parsing in the child process
1108 arg
.Replace("\"", "\\\"", true /* replace all */);
1110 // and quote any arguments containing the spaces to prevent them from
1111 // being broken down
1112 quote
= arg
.find_first_of(" \t") != wxString::npos
;
1116 command
+= '\"' + arg
+ '\"';
1126 return wxExecute(command
, flags
, handler
, env
);
1129 long wxExecute(char **argv
, int flags
, wxProcess
*handler
,
1130 const wxExecuteEnv
*env
)
1132 return wxExecuteImpl(argv
, flags
, handler
, env
);
1137 long wxExecute(wchar_t **argv
, int flags
, wxProcess
*handler
,
1138 const wxExecuteEnv
*env
)
1140 return wxExecuteImpl(argv
, flags
, handler
, env
);
1143 #endif // wxUSE_UNICODE