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__)
56 #if defined(__GNUWIN32__)
57 #include <sys/unistd.h>
61 #if !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
75 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
82 #include "wx/dde.h" // for WX_DDE hack in wxExecute
85 #include "wx/msw/private/hiddenwin.h"
87 // ----------------------------------------------------------------------------
89 // ----------------------------------------------------------------------------
91 // this message is sent when the process we're waiting for terminates
92 #define wxWM_PROC_TERMINATED (WM_USER + 10000)
94 // ----------------------------------------------------------------------------
95 // this module globals
96 // ----------------------------------------------------------------------------
98 // we need to create a hidden window to receive the process termination
99 // notifications and for this we need a (Win) class name for it which we will
100 // register the first time it's needed
101 static const wxChar
*wxMSWEXEC_WNDCLASSNAME
= wxT("_wxExecute_Internal_Class");
102 static const wxChar
*gs_classForHiddenWindow
= NULL
;
104 // event used to wake up threads waiting in wxExecuteThread
105 static HANDLE gs_heventShutdown
= NULL
;
107 // handles of all threads monitoring the execution of asynchronously running
109 static wxVector
<HANDLE
> gs_asyncThreads
;
111 // ----------------------------------------------------------------------------
113 // ----------------------------------------------------------------------------
115 // structure describing the process we're being waiting for
121 if ( !::CloseHandle(hProcess
) )
123 wxLogLastError(wxT("CloseHandle(hProcess)"));
127 HWND hWnd
; // window to send wxWM_PROC_TERMINATED to
128 HANDLE hProcess
; // handle of the process
129 DWORD dwProcessId
; // pid of the process
131 DWORD dwExitCode
; // the exit code of the process
132 bool state
; // set to false when the process finishes
135 class wxExecuteModule
: public wxModule
138 virtual bool OnInit() { return true; }
139 virtual void OnExit()
141 if ( gs_heventShutdown
)
143 // stop any threads waiting for the termination of asynchronously
145 if ( !::SetEvent(gs_heventShutdown
) )
147 wxLogDebug(wxT("Failed to set shutdown event in wxExecuteModule"));
150 ::CloseHandle(gs_heventShutdown
);
151 gs_heventShutdown
= NULL
;
153 // now wait until they terminate
154 if ( !gs_asyncThreads
.empty() )
156 const size_t numThreads
= gs_asyncThreads
.size();
158 if ( ::WaitForMultipleObjects
162 TRUE
, // wait for all of them to become signalled
163 3000 // long but finite value
166 wxLogDebug(wxT("Failed to stop all wxExecute monitor threads"));
169 for ( size_t n
= 0; n
< numThreads
; n
++ )
171 ::CloseHandle(gs_asyncThreads
[n
]);
174 gs_asyncThreads
.clear();
178 if ( gs_classForHiddenWindow
)
180 if ( !::UnregisterClass(wxMSWEXEC_WNDCLASSNAME
, wxGetInstance()) )
182 wxLogLastError(wxT("UnregisterClass(wxExecClass)"));
185 gs_classForHiddenWindow
= NULL
;
190 DECLARE_DYNAMIC_CLASS(wxExecuteModule
)
193 IMPLEMENT_DYNAMIC_CLASS(wxExecuteModule
, wxModule
)
195 #if wxUSE_STREAMS && !defined(__WXWINCE__)
197 // ----------------------------------------------------------------------------
199 // ----------------------------------------------------------------------------
201 class wxPipeInputStream
: public wxInputStream
204 wxPipeInputStream(HANDLE hInput
);
205 virtual ~wxPipeInputStream();
207 // returns true if the pipe is still opened
208 bool IsOpened() const { return m_hInput
!= INVALID_HANDLE_VALUE
; }
210 // returns true if there is any data to be read from the pipe
211 virtual bool CanRead() const;
214 size_t OnSysRead(void *buffer
, size_t len
);
219 wxDECLARE_NO_COPY_CLASS(wxPipeInputStream
);
222 class wxPipeOutputStream
: public wxOutputStream
225 wxPipeOutputStream(HANDLE hOutput
);
226 virtual ~wxPipeOutputStream() { Close(); }
230 size_t OnSysWrite(const void *buffer
, size_t len
);
235 wxDECLARE_NO_COPY_CLASS(wxPipeOutputStream
);
238 // define this to let wxexec.cpp know that we know what we're doing
239 #define _WX_USED_BY_WXEXECUTE_
240 #include "../common/execcmn.cpp"
242 // ----------------------------------------------------------------------------
243 // wxPipe represents a Win32 anonymous pipe
244 // ----------------------------------------------------------------------------
249 // the symbolic names for the pipe ends
256 // default ctor doesn't do anything
257 wxPipe() { m_handles
[Read
] = m_handles
[Write
] = INVALID_HANDLE_VALUE
; }
259 // create the pipe, return true if ok, false on error
262 // default secutiry attributes
263 SECURITY_ATTRIBUTES security
;
265 security
.nLength
= sizeof(security
);
266 security
.lpSecurityDescriptor
= NULL
;
267 security
.bInheritHandle
= TRUE
; // to pass it to the child
269 if ( !::CreatePipe(&m_handles
[0], &m_handles
[1], &security
, 0) )
271 wxLogSysError(_("Failed to create an anonymous pipe"));
279 // return true if we were created successfully
280 bool IsOk() const { return m_handles
[Read
] != INVALID_HANDLE_VALUE
; }
282 // return the descriptor for one of the pipe ends
283 HANDLE
operator[](Direction which
) const { return m_handles
[which
]; }
285 // detach a descriptor, meaning that the pipe dtor won't close it, and
287 HANDLE
Detach(Direction which
)
289 HANDLE handle
= m_handles
[which
];
290 m_handles
[which
] = INVALID_HANDLE_VALUE
;
295 // close the pipe descriptors
298 for ( size_t n
= 0; n
< WXSIZEOF(m_handles
); n
++ )
300 if ( m_handles
[n
] != INVALID_HANDLE_VALUE
)
302 ::CloseHandle(m_handles
[n
]);
303 m_handles
[n
] = INVALID_HANDLE_VALUE
;
308 // dtor closes the pipe descriptors
309 ~wxPipe() { Close(); }
315 #endif // wxUSE_STREAMS
317 // ============================================================================
319 // ============================================================================
321 // ----------------------------------------------------------------------------
322 // process termination detecting support
323 // ----------------------------------------------------------------------------
325 // thread function for the thread monitoring the process termination
326 static DWORD __stdcall
wxExecuteThread(void *arg
)
328 wxExecuteData
* const data
= (wxExecuteData
*)arg
;
330 // create the shutdown event if we're the first thread starting to wait
331 if ( !gs_heventShutdown
)
333 // create a manual initially non-signalled event object
334 gs_heventShutdown
= ::CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
335 if ( !gs_heventShutdown
)
337 wxLogDebug(wxT("CreateEvent() in wxExecuteThread failed"));
341 HANDLE handles
[2] = { data
->hProcess
, gs_heventShutdown
};
342 switch ( ::WaitForMultipleObjects(2, handles
, FALSE
, INFINITE
) )
345 // process terminated, get its exit code
346 if ( !::GetExitCodeProcess(data
->hProcess
, &data
->dwExitCode
) )
348 wxLogLastError(wxT("GetExitCodeProcess"));
351 wxASSERT_MSG( data
->dwExitCode
!= STILL_ACTIVE
,
352 wxT("process should have terminated") );
354 // send a message indicating process termination to the window
355 ::SendMessage(data
->hWnd
, wxWM_PROC_TERMINATED
, 0, (LPARAM
)data
);
358 case WAIT_OBJECT_0
+ 1:
359 // we're shutting down but the process is still running -- leave it
360 // run but clean up the associated data
365 //else: exiting while synchronously executing process is still
366 // running? this shouldn't happen...
370 wxLogDebug(wxT("Waiting for the process termination failed!"));
376 // window procedure of a hidden window which is created just to receive
377 // the notification message when a process exits
378 LRESULT APIENTRY _EXPORT
wxExecuteWindowCbk(HWND hWnd
, UINT message
,
379 WPARAM wParam
, LPARAM lParam
)
381 if ( message
== wxWM_PROC_TERMINATED
)
383 DestroyWindow(hWnd
); // we don't need it any more
385 wxExecuteData
* const data
= (wxExecuteData
*)lParam
;
388 data
->handler
->OnTerminate((int)data
->dwProcessId
,
389 (int)data
->dwExitCode
);
394 // we're executing synchronously, tell the waiting thread
395 // that the process finished
400 // asynchronous execution - we should do the clean up
408 return ::DefWindowProc(hWnd
, message
, wParam
, lParam
);
412 // ============================================================================
413 // implementation of IO redirection support classes
414 // ============================================================================
416 #if wxUSE_STREAMS && !defined(__WXWINCE__)
418 // ----------------------------------------------------------------------------
419 // wxPipeInputStreams
420 // ----------------------------------------------------------------------------
422 wxPipeInputStream::wxPipeInputStream(HANDLE hInput
)
427 wxPipeInputStream::~wxPipeInputStream()
429 if ( m_hInput
!= INVALID_HANDLE_VALUE
)
430 ::CloseHandle(m_hInput
);
433 bool wxPipeInputStream::CanRead() const
435 // we can read if there's something in the put back buffer
436 // even pipe is closed
437 if ( m_wbacksize
> m_wbackcur
)
440 wxPipeInputStream
* const self
= wxConstCast(this, wxPipeInputStream
);
444 // set back to mark Eof as it may have been unset by Ungetch()
445 self
->m_lasterror
= wxSTREAM_EOF
;
451 // function name is misleading, it works with anon pipes as well
452 DWORD rc
= ::PeekNamedPipe
455 NULL
, 0, // ptr to buffer and its size
456 NULL
, // [out] bytes read
457 &nAvailable
, // [out] bytes available
458 NULL
// [out] bytes left
463 if ( ::GetLastError() != ERROR_BROKEN_PIPE
)
466 wxLogLastError(wxT("PeekNamedPipe"));
469 // don't try to continue reading from a pipe if an error occurred or if
470 // it had been closed
471 ::CloseHandle(m_hInput
);
473 self
->m_hInput
= INVALID_HANDLE_VALUE
;
474 self
->m_lasterror
= wxSTREAM_EOF
;
479 return nAvailable
!= 0;
482 size_t wxPipeInputStream::OnSysRead(void *buffer
, size_t len
)
486 m_lasterror
= wxSTREAM_EOF
;
492 if ( !::ReadFile(m_hInput
, buffer
, len
, &bytesRead
, NULL
) )
494 m_lasterror
= ::GetLastError() == ERROR_BROKEN_PIPE
496 : wxSTREAM_READ_ERROR
;
499 // bytesRead is set to 0, as desired, if an error occurred
503 // ----------------------------------------------------------------------------
504 // wxPipeOutputStream
505 // ----------------------------------------------------------------------------
507 wxPipeOutputStream::wxPipeOutputStream(HANDLE hOutput
)
511 // unblock the pipe to prevent deadlocks when we're writing to the pipe
512 // from which the child process can't read because it is writing in its own
514 DWORD mode
= PIPE_READMODE_BYTE
| PIPE_NOWAIT
;
515 if ( !::SetNamedPipeHandleState
519 NULL
, // collection count (we don't set it)
520 NULL
// timeout (we don't set it neither)
523 wxLogLastError(wxT("SetNamedPipeHandleState(PIPE_NOWAIT)"));
527 bool wxPipeOutputStream::Close()
529 return ::CloseHandle(m_hOutput
) != 0;
533 size_t wxPipeOutputStream::OnSysWrite(const void *buffer
, size_t len
)
535 m_lasterror
= wxSTREAM_NO_ERROR
;
537 DWORD totalWritten
= 0;
541 if ( !::WriteFile(m_hOutput
, buffer
, len
, &chunkWritten
, NULL
) )
543 m_lasterror
= ::GetLastError() == ERROR_BROKEN_PIPE
545 : wxSTREAM_WRITE_ERROR
;
552 buffer
= (char *)buffer
+ chunkWritten
;
553 totalWritten
+= chunkWritten
;
560 #endif // wxUSE_STREAMS
562 // ============================================================================
563 // wxExecute functions family
564 // ============================================================================
568 // connect to the given server via DDE and ask it to execute the command
570 wxExecuteDDE(const wxString
& ddeServer
,
571 const wxString
& ddeTopic
,
572 const wxString
& ddeCommand
)
574 bool ok
wxDUMMY_INITIALIZE(false);
578 conn
= client
.MakeConnection(wxEmptyString
, ddeServer
, ddeTopic
);
583 else // connected to DDE server
585 // the added complication here is that although most programs use
586 // XTYP_EXECUTE for their DDE API, some important ones -- like Word
587 // and other MS stuff - use XTYP_REQUEST!
589 // moreover, anotheri mportant program (IE) understands both but
590 // returns an error from Execute() so we must try Request() first
591 // to avoid doing it twice
593 // we're prepared for this one to fail, so don't show errors
596 ok
= conn
->Request(ddeCommand
) != NULL
;
601 // now try execute -- but show the errors
602 ok
= conn
->Execute(ddeCommand
);
611 long wxExecute(const wxString
& cmd
, int flags
, wxProcess
*handler
,
612 const wxExecuteEnv
*env
)
614 wxCHECK_MSG( !cmd
.empty(), 0, wxT("empty command in wxExecute") );
617 // for many reasons, the code below breaks down if it's called from another
618 // thread -- this could be fixed, but as Unix versions don't support this
619 // neither I don't want to waste time on this now
620 wxASSERT_MSG( wxThread::IsMain(),
621 wxT("wxExecute() can be called only from the main thread") );
622 #endif // wxUSE_THREADS
627 // DDE hack: this is really not pretty, but we need to allow this for
628 // transparent handling of DDE servers in wxMimeTypesManager. Usually it
629 // returns the command which should be run to view/open/... a file of the
630 // given type. Sometimes, however, this command just launches the server
631 // and an additional DDE request must be made to really open the file. To
632 // keep all this well hidden from the application, we allow a special form
633 // of command: WX_DDE#<command>#DDE_SERVER#DDE_TOPIC#DDE_COMMAND in which
634 // case we execute just <command> and process the rest below
635 wxString ddeServer
, ddeTopic
, ddeCommand
;
636 static const size_t lenDdePrefix
= 7; // strlen("WX_DDE:")
637 if ( cmd
.Left(lenDdePrefix
) == wxT("WX_DDE#") )
639 // speed up the concatenations below
640 ddeServer
.reserve(256);
641 ddeTopic
.reserve(256);
642 ddeCommand
.reserve(256);
644 const wxChar
*p
= cmd
.c_str() + 7;
645 while ( *p
&& *p
!= wxT('#') )
657 wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute"));
660 while ( *p
&& *p
!= wxT('#') )
672 wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute"));
675 while ( *p
&& *p
!= wxT('#') )
687 wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute"));
695 // if we want to just launch the program and not wait for its
696 // termination, try to execute DDE command right now, it can succeed if
697 // the process is already running - but as it fails if it's not
698 // running, suppress any errors it might generate
699 if ( !(flags
& wxEXEC_SYNC
) )
702 if ( wxExecuteDDE(ddeServer
, ddeTopic
, ddeCommand
) )
704 // a dummy PID - this is a hack, of course, but it's well worth
705 // it as we don't open a new server each time we're called
706 // which would be quite bad
718 // the IO redirection is only supported with wxUSE_STREAMS
719 BOOL redirect
= FALSE
;
721 #if wxUSE_STREAMS && !defined(__WXWINCE__)
722 wxPipe pipeIn
, pipeOut
, pipeErr
;
724 // we'll save here the copy of pipeIn[Write]
725 HANDLE hpipeStdinWrite
= INVALID_HANDLE_VALUE
;
727 // open the pipes to which child process IO will be redirected if needed
728 if ( handler
&& handler
->IsRedirected() )
730 // create pipes for redirecting stdin, stdout and stderr
731 if ( !pipeIn
.Create() || !pipeOut
.Create() || !pipeErr
.Create() )
733 wxLogSysError(_("Failed to redirect the child process IO"));
735 // indicate failure: we need to return different error code
736 // depending on the sync flag
737 return flags
& wxEXEC_SYNC
? -1 : 0;
742 #endif // wxUSE_STREAMS
744 // create the process
749 #if wxUSE_STREAMS && !defined(__WXWINCE__)
752 si
.dwFlags
= STARTF_USESTDHANDLES
;
754 si
.hStdInput
= pipeIn
[wxPipe::Read
];
755 si
.hStdOutput
= pipeOut
[wxPipe::Write
];
756 si
.hStdError
= pipeErr
[wxPipe::Write
];
758 // we must duplicate the handle to the write side of stdin pipe to make
759 // it non inheritable: indeed, we must close the writing end of pipeIn
760 // before launching the child process as otherwise this handle will be
761 // inherited by the child which will never close it and so the pipe
762 // will never be closed and the child will be left stuck in ReadFile()
763 HANDLE pipeInWrite
= pipeIn
.Detach(wxPipe::Write
);
764 if ( !::DuplicateHandle
766 ::GetCurrentProcess(),
768 ::GetCurrentProcess(),
770 0, // desired access: unused here
771 FALSE
, // not inherited
772 DUPLICATE_SAME_ACCESS
// same access as for src handle
775 wxLogLastError(wxT("DuplicateHandle"));
778 ::CloseHandle(pipeInWrite
);
780 #endif // wxUSE_STREAMS
782 // The default logic for showing the console is to show it only if the IO
783 // is not redirected however wxEXEC_{SHOW,HIDE}_CONSOLE flags can be
784 // explicitly specified to change it.
785 if ( (flags
& wxEXEC_HIDE_CONSOLE
) ||
786 (redirect
&& !(flags
& wxEXEC_SHOW_CONSOLE
)) )
788 si
.dwFlags
|= STARTF_USESHOWWINDOW
;
789 si
.wShowWindow
= SW_HIDE
;
793 PROCESS_INFORMATION pi
;
794 DWORD dwFlags
= CREATE_SUSPENDED
;
797 if ( (flags
& wxEXEC_MAKE_GROUP_LEADER
) &&
798 (wxGetOsVersion() == wxOS_WINDOWS_NT
) )
799 dwFlags
|= CREATE_NEW_PROCESS_GROUP
;
801 dwFlags
|= CREATE_DEFAULT_ERROR_MODE
;
803 // we are assuming commands without spaces for now
804 wxString moduleName
= command
.BeforeFirst(wxT(' '));
805 wxString arguments
= command
.AfterFirst(wxT(' '));
808 wxWxCharBuffer envBuffer
;
812 useCwd
= !env
->cwd
.empty();
814 // Translate environment variable map into NUL-terminated list of
815 // NUL-terminated strings.
816 if ( !env
->env
.empty() )
819 // Environment variables can contain non-ASCII characters. We could
820 // check for it and not use this flag if everything is really ASCII
821 // only but there doesn't seem to be any reason to do it so just
822 // assume Unicode by default.
823 dwFlags
|= CREATE_UNICODE_ENVIRONMENT
;
824 #endif // wxUSE_UNICODE
826 wxEnvVariableHashMap::const_iterator it
;
828 size_t envSz
= 1; // ending '\0'
829 for ( it
= env
->env
.begin(); it
!= env
->env
.end(); ++it
)
831 // Add size of env variable name and value, and '=' char and
833 envSz
+= it
->first
.length() + it
->second
.length() + 2;
836 envBuffer
.extend(envSz
);
838 wxChar
*p
= envBuffer
.data();
839 for ( it
= env
->env
.begin(); it
!= env
->env
.end(); ++it
)
841 const wxString line
= it
->first
+ wxS("=") + it
->second
;
843 // Include the trailing NUL which will always terminate the
844 // buffer returned by t_str().
845 const size_t len
= line
.length() + 1;
847 wxTmemcpy(p
, line
.t_str(), len
);
852 // And another NUL to terminate the list of NUL-terminated strings.
857 bool ok
= ::CreateProcess
859 // WinCE requires appname to be non null
860 // Win32 allows for null
863 moduleName
.wx_str(),// application name
865 arguments
.wx_str(), // arguments
867 NULL
, // application name (use only cmd line)
869 command
.wx_str(), // full command line
871 NULL
, // security attributes: defaults for both
872 NULL
, // the process and its main thread
873 redirect
, // inherit handles if we use pipes
874 dwFlags
, // process creation flags
875 envBuffer
.data(), // environment (may be NULL which is fine)
876 useCwd
// initial working directory
877 ? const_cast<wxChar
*>(env
->cwd
.wx_str())
878 : NULL
, // (or use the same)
879 &si
, // startup info (unused here)
883 #if wxUSE_STREAMS && !defined(__WXWINCE__)
884 // we can close the pipe ends used by child anyhow
887 ::CloseHandle(pipeIn
.Detach(wxPipe::Read
));
888 ::CloseHandle(pipeOut
.Detach(wxPipe::Write
));
889 ::CloseHandle(pipeErr
.Detach(wxPipe::Write
));
891 #endif // wxUSE_STREAMS
895 #if wxUSE_STREAMS && !defined(__WXWINCE__)
896 // close the other handles too
899 ::CloseHandle(pipeOut
.Detach(wxPipe::Read
));
900 ::CloseHandle(pipeErr
.Detach(wxPipe::Read
));
902 #endif // wxUSE_STREAMS
904 wxLogSysError(_("Execution of command '%s' failed"), command
.c_str());
906 return flags
& wxEXEC_SYNC
? -1 : 0;
909 #if wxUSE_STREAMS && !defined(__WXWINCE__)
910 // the input buffer bufOut is connected to stdout, this is why it is
911 // called bufOut and not bufIn
912 wxStreamTempInputBuffer bufOut
,
917 // We can now initialize the wxStreams
919 outStream
= new wxPipeInputStream(pipeOut
.Detach(wxPipe::Read
));
921 errStream
= new wxPipeInputStream(pipeErr
.Detach(wxPipe::Read
));
923 inStream
= new wxPipeOutputStream(hpipeStdinWrite
);
925 handler
->SetPipeStreams(outStream
, inStream
, errStream
);
927 bufOut
.Init(outStream
);
928 bufErr
.Init(errStream
);
930 #endif // wxUSE_STREAMS
932 // create a hidden window to receive notification about process
934 HWND hwnd
= wxCreateHiddenWindow
936 &gs_classForHiddenWindow
,
937 wxMSWEXEC_WNDCLASSNAME
,
938 (WNDPROC
)wxExecuteWindowCbk
941 wxASSERT_MSG( hwnd
, wxT("can't create a hidden window for wxExecute") );
944 wxExecuteData
*data
= new wxExecuteData
;
945 data
->hProcess
= pi
.hProcess
;
946 data
->dwProcessId
= pi
.dwProcessId
;
948 data
->state
= (flags
& wxEXEC_SYNC
) != 0;
949 if ( flags
& wxEXEC_SYNC
)
951 // handler may be !NULL for capturing program output, but we don't use
952 // it wxExecuteData struct in this case
953 data
->handler
= NULL
;
957 // may be NULL or not
958 data
->handler
= handler
;
961 handler
->SetPid(pi
.dwProcessId
);
965 HANDLE hThread
= ::CreateThread(NULL
,
972 // resume process we created now - whether the thread creation succeeded or
974 if ( ::ResumeThread(pi
.hThread
) == (DWORD
)-1 )
976 // ignore it - what can we do?
977 wxLogLastError(wxT("ResumeThread in wxExecute"));
980 // close unneeded handle
981 if ( !::CloseHandle(pi
.hThread
) )
983 wxLogLastError(wxT("CloseHandle(hThread)"));
988 wxLogLastError(wxT("CreateThread in wxExecute"));
993 // the process still started up successfully...
994 return pi
.dwProcessId
;
997 gs_asyncThreads
.push_back(hThread
);
999 #if wxUSE_IPC && !defined(__WXWINCE__)
1000 // second part of DDE hack: now establish the DDE conversation with the
1001 // just launched process
1002 if ( !ddeServer
.empty() )
1006 // give the process the time to init itself
1008 // we use a very big timeout hoping that WaitForInputIdle() will return
1009 // much sooner, but not INFINITE just in case the process hangs
1010 // completely - like this we will regain control sooner or later
1011 switch ( ::WaitForInputIdle(pi
.hProcess
, 10000 /* 10 seconds */) )
1014 wxFAIL_MSG( wxT("unexpected WaitForInputIdle() return code") );
1018 wxLogLastError(wxT("WaitForInputIdle() in wxExecute"));
1021 wxLogDebug(wxT("Timeout too small in WaitForInputIdle"));
1027 // ok, process ready to accept DDE requests
1028 ok
= wxExecuteDDE(ddeServer
, ddeTopic
, ddeCommand
);
1033 wxLogDebug(wxT("Failed to send DDE request to the process \"%s\"."),
1039 if ( !(flags
& wxEXEC_SYNC
) )
1041 // clean up will be done when the process terminates
1044 return pi
.dwProcessId
;
1047 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
1048 wxCHECK_MSG( traits
, -1, wxT("no wxAppTraits in wxExecute()?") );
1050 void *cookie
= NULL
;
1051 if ( !(flags
& wxEXEC_NODISABLE
) )
1053 // disable all app windows while waiting for the child process to finish
1054 cookie
= traits
->BeforeChildWaitLoop();
1057 // wait until the child process terminates
1058 while ( data
->state
)
1060 #if wxUSE_STREAMS && !defined(__WXWINCE__)
1061 if ( !bufOut
.Update() && !bufErr
.Update() )
1062 #endif // wxUSE_STREAMS
1064 // don't eat 100% of the CPU -- ugly but anything else requires
1065 // real async IO which we don't have for the moment
1069 // we must always process messages for our hidden window or we'd never
1070 // get wxWM_PROC_TERMINATED and so this loop would never terminate
1072 ::PeekMessage(&msg
, data
->hWnd
, 0, 0, PM_REMOVE
);
1074 // we may also need to process messages for all the other application
1076 if ( !(flags
& wxEXEC_NOEVENTS
) )
1078 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
1084 if ( !(flags
& wxEXEC_NODISABLE
) )
1086 // reenable disabled windows back
1087 traits
->AfterChildWaitLoop(cookie
);
1090 DWORD dwExitCode
= data
->dwExitCode
;
1093 // return the exit code
1097 template <typename CharType
>
1098 long wxExecuteImpl(CharType
**argv
, int flags
, wxProcess
*handler
,
1099 const wxExecuteEnv
*env
)
1102 command
.reserve(1024);
1112 // we need to quote empty arguments, otherwise they'd just
1118 // escape any quotes present in the string to avoid interfering
1119 // with the command line parsing in the child process
1120 arg
.Replace("\"", "\\\"", true /* replace all */);
1122 // and quote any arguments containing the spaces to prevent them from
1123 // being broken down
1124 quote
= arg
.find_first_of(" \t") != wxString::npos
;
1128 command
+= '\"' + arg
+ '\"';
1138 return wxExecute(command
, flags
, handler
, env
);
1141 long wxExecute(char **argv
, int flags
, wxProcess
*handler
,
1142 const wxExecuteEnv
*env
)
1144 return wxExecuteImpl(argv
, flags
, handler
, env
);
1149 long wxExecute(wchar_t **argv
, int flags
, wxProcess
*handler
,
1150 const wxExecuteEnv
*env
)
1152 return wxExecuteImpl(argv
, flags
, handler
, env
);
1155 #endif // wxUSE_UNICODE