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 // implemented in utils.cpp
86 extern "C" WXDLLIMPEXP_BASE HWND
87 wxCreateHiddenWindow(LPCTSTR
*pclassname
, LPCTSTR classname
, WNDPROC wndproc
);
89 // ----------------------------------------------------------------------------
91 // ----------------------------------------------------------------------------
93 // this message is sent when the process we're waiting for terminates
94 #define wxWM_PROC_TERMINATED (WM_USER + 10000)
96 // ----------------------------------------------------------------------------
97 // this module globals
98 // ----------------------------------------------------------------------------
100 // we need to create a hidden window to receive the process termination
101 // notifications and for this we need a (Win) class name for it which we will
102 // register the first time it's needed
103 static const wxChar
*wxMSWEXEC_WNDCLASSNAME
= wxT("_wxExecute_Internal_Class");
104 static const wxChar
*gs_classForHiddenWindow
= NULL
;
106 // event used to wake up threads waiting in wxExecuteThread
107 static HANDLE gs_heventShutdown
= NULL
;
109 // handles of all threads monitoring the execution of asynchronously running
111 static wxVector
<HANDLE
> gs_asyncThreads
;
113 // ----------------------------------------------------------------------------
115 // ----------------------------------------------------------------------------
117 // structure describing the process we're being waiting for
123 if ( !::CloseHandle(hProcess
) )
125 wxLogLastError(wxT("CloseHandle(hProcess)"));
129 HWND hWnd
; // window to send wxWM_PROC_TERMINATED to
130 HANDLE hProcess
; // handle of the process
131 DWORD dwProcessId
; // pid of the process
133 DWORD dwExitCode
; // the exit code of the process
134 bool state
; // set to false when the process finishes
137 class wxExecuteModule
: public wxModule
140 virtual bool OnInit() { return true; }
141 virtual void OnExit()
143 if ( gs_heventShutdown
)
145 // stop any threads waiting for the termination of asynchronously
147 if ( !::SetEvent(gs_heventShutdown
) )
149 wxLogDebug(wxT("Failed to set shutdown event in wxExecuteModule"));
152 ::CloseHandle(gs_heventShutdown
);
153 gs_heventShutdown
= NULL
;
155 // now wait until they terminate
156 if ( !gs_asyncThreads
.empty() )
158 const size_t numThreads
= gs_asyncThreads
.size();
160 if ( ::WaitForMultipleObjects
164 TRUE
, // wait for all of them to become signalled
165 3000 // long but finite value
168 wxLogDebug(wxT("Failed to stop all wxExecute monitor threads"));
171 for ( size_t n
= 0; n
< numThreads
; n
++ )
173 ::CloseHandle(gs_asyncThreads
[n
]);
176 gs_asyncThreads
.clear();
180 if ( gs_classForHiddenWindow
)
182 if ( !::UnregisterClass(wxMSWEXEC_WNDCLASSNAME
, wxGetInstance()) )
184 wxLogLastError(wxT("UnregisterClass(wxExecClass)"));
187 gs_classForHiddenWindow
= NULL
;
192 DECLARE_DYNAMIC_CLASS(wxExecuteModule
)
195 IMPLEMENT_DYNAMIC_CLASS(wxExecuteModule
, wxModule
)
197 #if wxUSE_STREAMS && !defined(__WXWINCE__)
199 // ----------------------------------------------------------------------------
201 // ----------------------------------------------------------------------------
203 class wxPipeInputStream
: public wxInputStream
206 wxPipeInputStream(HANDLE hInput
);
207 virtual ~wxPipeInputStream();
209 // returns true if the pipe is still opened
210 bool IsOpened() const { return m_hInput
!= INVALID_HANDLE_VALUE
; }
212 // returns true if there is any data to be read from the pipe
213 virtual bool CanRead() const;
216 size_t OnSysRead(void *buffer
, size_t len
);
221 wxDECLARE_NO_COPY_CLASS(wxPipeInputStream
);
224 class wxPipeOutputStream
: public wxOutputStream
227 wxPipeOutputStream(HANDLE hOutput
);
228 virtual ~wxPipeOutputStream() { Close(); }
232 size_t OnSysWrite(const void *buffer
, size_t len
);
237 wxDECLARE_NO_COPY_CLASS(wxPipeOutputStream
);
240 // define this to let wxexec.cpp know that we know what we're doing
241 #define _WX_USED_BY_WXEXECUTE_
242 #include "../common/execcmn.cpp"
244 // ----------------------------------------------------------------------------
245 // wxPipe represents a Win32 anonymous pipe
246 // ----------------------------------------------------------------------------
251 // the symbolic names for the pipe ends
258 // default ctor doesn't do anything
259 wxPipe() { m_handles
[Read
] = m_handles
[Write
] = INVALID_HANDLE_VALUE
; }
261 // create the pipe, return true if ok, false on error
264 // default secutiry attributes
265 SECURITY_ATTRIBUTES security
;
267 security
.nLength
= sizeof(security
);
268 security
.lpSecurityDescriptor
= NULL
;
269 security
.bInheritHandle
= TRUE
; // to pass it to the child
271 if ( !::CreatePipe(&m_handles
[0], &m_handles
[1], &security
, 0) )
273 wxLogSysError(_("Failed to create an anonymous pipe"));
281 // return true if we were created successfully
282 bool IsOk() const { return m_handles
[Read
] != INVALID_HANDLE_VALUE
; }
284 // return the descriptor for one of the pipe ends
285 HANDLE
operator[](Direction which
) const { return m_handles
[which
]; }
287 // detach a descriptor, meaning that the pipe dtor won't close it, and
289 HANDLE
Detach(Direction which
)
291 HANDLE handle
= m_handles
[which
];
292 m_handles
[which
] = INVALID_HANDLE_VALUE
;
297 // close the pipe descriptors
300 for ( size_t n
= 0; n
< WXSIZEOF(m_handles
); n
++ )
302 if ( m_handles
[n
] != INVALID_HANDLE_VALUE
)
304 ::CloseHandle(m_handles
[n
]);
305 m_handles
[n
] = INVALID_HANDLE_VALUE
;
310 // dtor closes the pipe descriptors
311 ~wxPipe() { Close(); }
317 #endif // wxUSE_STREAMS
319 // ============================================================================
321 // ============================================================================
323 // ----------------------------------------------------------------------------
324 // process termination detecting support
325 // ----------------------------------------------------------------------------
327 // thread function for the thread monitoring the process termination
328 static DWORD __stdcall
wxExecuteThread(void *arg
)
330 wxExecuteData
* const data
= (wxExecuteData
*)arg
;
332 // create the shutdown event if we're the first thread starting to wait
333 if ( !gs_heventShutdown
)
335 // create a manual initially non-signalled event object
336 gs_heventShutdown
= ::CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
337 if ( !gs_heventShutdown
)
339 wxLogDebug(wxT("CreateEvent() in wxExecuteThread failed"));
343 HANDLE handles
[2] = { data
->hProcess
, gs_heventShutdown
};
344 switch ( ::WaitForMultipleObjects(2, handles
, FALSE
, INFINITE
) )
347 // process terminated, get its exit code
348 if ( !::GetExitCodeProcess(data
->hProcess
, &data
->dwExitCode
) )
350 wxLogLastError(wxT("GetExitCodeProcess"));
353 wxASSERT_MSG( data
->dwExitCode
!= STILL_ACTIVE
,
354 wxT("process should have terminated") );
356 // send a message indicating process termination to the window
357 ::SendMessage(data
->hWnd
, wxWM_PROC_TERMINATED
, 0, (LPARAM
)data
);
360 case WAIT_OBJECT_0
+ 1:
361 // we're shutting down but the process is still running -- leave it
362 // run but clean up the associated data
367 //else: exiting while synchronously executing process is still
368 // running? this shouldn't happen...
372 wxLogDebug(wxT("Waiting for the process termination failed!"));
378 // window procedure of a hidden window which is created just to receive
379 // the notification message when a process exits
380 LRESULT APIENTRY _EXPORT
wxExecuteWindowCbk(HWND hWnd
, UINT message
,
381 WPARAM wParam
, LPARAM lParam
)
383 if ( message
== wxWM_PROC_TERMINATED
)
385 DestroyWindow(hWnd
); // we don't need it any more
387 wxExecuteData
* const data
= (wxExecuteData
*)lParam
;
390 data
->handler
->OnTerminate((int)data
->dwProcessId
,
391 (int)data
->dwExitCode
);
396 // we're executing synchronously, tell the waiting thread
397 // that the process finished
402 // asynchronous execution - we should do the clean up
410 return ::DefWindowProc(hWnd
, message
, wParam
, lParam
);
414 // ============================================================================
415 // implementation of IO redirection support classes
416 // ============================================================================
418 #if wxUSE_STREAMS && !defined(__WXWINCE__)
420 // ----------------------------------------------------------------------------
421 // wxPipeInputStreams
422 // ----------------------------------------------------------------------------
424 wxPipeInputStream::wxPipeInputStream(HANDLE hInput
)
429 wxPipeInputStream::~wxPipeInputStream()
431 if ( m_hInput
!= INVALID_HANDLE_VALUE
)
432 ::CloseHandle(m_hInput
);
435 bool wxPipeInputStream::CanRead() const
437 // we can read if there's something in the put back buffer
438 // even pipe is closed
439 if ( m_wbacksize
> m_wbackcur
)
442 wxPipeInputStream
* const self
= wxConstCast(this, wxPipeInputStream
);
446 // set back to mark Eof as it may have been unset by Ungetch()
447 self
->m_lasterror
= wxSTREAM_EOF
;
453 // function name is misleading, it works with anon pipes as well
454 DWORD rc
= ::PeekNamedPipe
457 NULL
, 0, // ptr to buffer and its size
458 NULL
, // [out] bytes read
459 &nAvailable
, // [out] bytes available
460 NULL
// [out] bytes left
465 if ( ::GetLastError() != ERROR_BROKEN_PIPE
)
468 wxLogLastError(wxT("PeekNamedPipe"));
471 // don't try to continue reading from a pipe if an error occurred or if
472 // it had been closed
473 ::CloseHandle(m_hInput
);
475 self
->m_hInput
= INVALID_HANDLE_VALUE
;
476 self
->m_lasterror
= wxSTREAM_EOF
;
481 return nAvailable
!= 0;
484 size_t wxPipeInputStream::OnSysRead(void *buffer
, size_t len
)
488 m_lasterror
= wxSTREAM_EOF
;
494 if ( !::ReadFile(m_hInput
, buffer
, len
, &bytesRead
, NULL
) )
496 m_lasterror
= ::GetLastError() == ERROR_BROKEN_PIPE
498 : wxSTREAM_READ_ERROR
;
501 // bytesRead is set to 0, as desired, if an error occurred
505 // ----------------------------------------------------------------------------
506 // wxPipeOutputStream
507 // ----------------------------------------------------------------------------
509 wxPipeOutputStream::wxPipeOutputStream(HANDLE hOutput
)
513 // unblock the pipe to prevent deadlocks when we're writing to the pipe
514 // from which the child process can't read because it is writing in its own
516 DWORD mode
= PIPE_READMODE_BYTE
| PIPE_NOWAIT
;
517 if ( !::SetNamedPipeHandleState
521 NULL
, // collection count (we don't set it)
522 NULL
// timeout (we don't set it neither)
525 wxLogLastError(wxT("SetNamedPipeHandleState(PIPE_NOWAIT)"));
529 bool wxPipeOutputStream::Close()
531 return ::CloseHandle(m_hOutput
) != 0;
535 size_t wxPipeOutputStream::OnSysWrite(const void *buffer
, size_t len
)
537 m_lasterror
= wxSTREAM_NO_ERROR
;
539 DWORD totalWritten
= 0;
543 if ( !::WriteFile(m_hOutput
, buffer
, len
, &chunkWritten
, NULL
) )
545 m_lasterror
= ::GetLastError() == ERROR_BROKEN_PIPE
547 : wxSTREAM_WRITE_ERROR
;
554 buffer
= (char *)buffer
+ chunkWritten
;
555 totalWritten
+= chunkWritten
;
562 #endif // wxUSE_STREAMS
564 // ============================================================================
565 // wxExecute functions family
566 // ============================================================================
570 // connect to the given server via DDE and ask it to execute the command
572 wxExecuteDDE(const wxString
& ddeServer
,
573 const wxString
& ddeTopic
,
574 const wxString
& ddeCommand
)
576 bool ok
wxDUMMY_INITIALIZE(false);
580 conn
= client
.MakeConnection(wxEmptyString
, ddeServer
, ddeTopic
);
585 else // connected to DDE server
587 // the added complication here is that although most programs use
588 // XTYP_EXECUTE for their DDE API, some important ones -- like Word
589 // and other MS stuff - use XTYP_REQUEST!
591 // moreover, anotheri mportant program (IE) understands both but
592 // returns an error from Execute() so we must try Request() first
593 // to avoid doing it twice
595 // we're prepared for this one to fail, so don't show errors
598 ok
= conn
->Request(ddeCommand
) != NULL
;
603 // now try execute -- but show the errors
604 ok
= conn
->Execute(ddeCommand
);
613 long wxExecute(const wxString
& cmd
, int flags
, wxProcess
*handler
,
614 const wxExecuteEnv
*env
)
616 wxCHECK_MSG( !cmd
.empty(), 0, wxT("empty command in wxExecute") );
619 // for many reasons, the code below breaks down if it's called from another
620 // thread -- this could be fixed, but as Unix versions don't support this
621 // neither I don't want to waste time on this now
622 wxASSERT_MSG( wxThread::IsMain(),
623 wxT("wxExecute() can be called only from the main thread") );
624 #endif // wxUSE_THREADS
629 // DDE hack: this is really not pretty, but we need to allow this for
630 // transparent handling of DDE servers in wxMimeTypesManager. Usually it
631 // returns the command which should be run to view/open/... a file of the
632 // given type. Sometimes, however, this command just launches the server
633 // and an additional DDE request must be made to really open the file. To
634 // keep all this well hidden from the application, we allow a special form
635 // of command: WX_DDE#<command>#DDE_SERVER#DDE_TOPIC#DDE_COMMAND in which
636 // case we execute just <command> and process the rest below
637 wxString ddeServer
, ddeTopic
, ddeCommand
;
638 static const size_t lenDdePrefix
= 7; // strlen("WX_DDE:")
639 if ( cmd
.Left(lenDdePrefix
) == wxT("WX_DDE#") )
641 // speed up the concatenations below
642 ddeServer
.reserve(256);
643 ddeTopic
.reserve(256);
644 ddeCommand
.reserve(256);
646 const wxChar
*p
= cmd
.c_str() + 7;
647 while ( *p
&& *p
!= wxT('#') )
659 wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute"));
662 while ( *p
&& *p
!= wxT('#') )
674 wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute"));
677 while ( *p
&& *p
!= wxT('#') )
689 wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute"));
697 // if we want to just launch the program and not wait for its
698 // termination, try to execute DDE command right now, it can succeed if
699 // the process is already running - but as it fails if it's not
700 // running, suppress any errors it might generate
701 if ( !(flags
& wxEXEC_SYNC
) )
704 if ( wxExecuteDDE(ddeServer
, ddeTopic
, ddeCommand
) )
706 // a dummy PID - this is a hack, of course, but it's well worth
707 // it as we don't open a new server each time we're called
708 // which would be quite bad
720 // the IO redirection is only supported with wxUSE_STREAMS
721 BOOL redirect
= FALSE
;
723 #if wxUSE_STREAMS && !defined(__WXWINCE__)
724 wxPipe pipeIn
, pipeOut
, pipeErr
;
726 // we'll save here the copy of pipeIn[Write]
727 HANDLE hpipeStdinWrite
= INVALID_HANDLE_VALUE
;
729 // open the pipes to which child process IO will be redirected if needed
730 if ( handler
&& handler
->IsRedirected() )
732 // create pipes for redirecting stdin, stdout and stderr
733 if ( !pipeIn
.Create() || !pipeOut
.Create() || !pipeErr
.Create() )
735 wxLogSysError(_("Failed to redirect the child process IO"));
737 // indicate failure: we need to return different error code
738 // depending on the sync flag
739 return flags
& wxEXEC_SYNC
? -1 : 0;
744 #endif // wxUSE_STREAMS
746 // create the process
751 #if wxUSE_STREAMS && !defined(__WXWINCE__)
754 si
.dwFlags
= STARTF_USESTDHANDLES
;
756 si
.hStdInput
= pipeIn
[wxPipe::Read
];
757 si
.hStdOutput
= pipeOut
[wxPipe::Write
];
758 si
.hStdError
= pipeErr
[wxPipe::Write
];
760 // when the std IO is redirected, we don't show the (console) process
761 // window by default, but this can be overridden by the caller by
762 // specifying wxEXEC_NOHIDE flag
763 if ( !(flags
& wxEXEC_NOHIDE
) )
765 si
.dwFlags
|= STARTF_USESHOWWINDOW
;
766 si
.wShowWindow
= SW_HIDE
;
769 // we must duplicate the handle to the write side of stdin pipe to make
770 // it non inheritable: indeed, we must close the writing end of pipeIn
771 // before launching the child process as otherwise this handle will be
772 // inherited by the child which will never close it and so the pipe
773 // will never be closed and the child will be left stuck in ReadFile()
774 HANDLE pipeInWrite
= pipeIn
.Detach(wxPipe::Write
);
775 if ( !::DuplicateHandle
777 ::GetCurrentProcess(),
779 ::GetCurrentProcess(),
781 0, // desired access: unused here
782 FALSE
, // not inherited
783 DUPLICATE_SAME_ACCESS
// same access as for src handle
786 wxLogLastError(wxT("DuplicateHandle"));
789 ::CloseHandle(pipeInWrite
);
791 #endif // wxUSE_STREAMS
793 PROCESS_INFORMATION pi
;
794 DWORD dwFlags
= CREATE_SUSPENDED
;
797 dwFlags
|= CREATE_DEFAULT_ERROR_MODE
;
799 // we are assuming commands without spaces for now
800 wxString moduleName
= command
.BeforeFirst(wxT(' '));
801 wxString arguments
= command
.AfterFirst(wxT(' '));
804 wxWxCharBuffer envBuffer
;
808 useCwd
= !env
->cwd
.empty();
810 // Translate environment variable map into NUL-terminated list of
811 // NUL-terminated strings.
812 if ( !env
->env
.empty() )
815 // Environment variables can contain non-ASCII characters. We could
816 // check for it and not use this flag if everything is really ASCII
817 // only but there doesn't seem to be any reason to do it so just
818 // assume Unicode by default.
819 dwFlags
|= CREATE_UNICODE_ENVIRONMENT
;
820 #endif // wxUSE_UNICODE
822 wxEnvVariableHashMap::const_iterator it
;
824 size_t envSz
= 1; // ending '\0'
825 for ( it
= env
->env
.begin(); it
!= env
->env
.end(); ++it
)
827 // Add size of env variable name and value, and '=' char and
829 envSz
+= it
->first
.length() + it
->second
.length() + 2;
832 envBuffer
.extend(envSz
);
834 wxChar
*p
= envBuffer
.data();
835 for ( it
= env
->env
.begin(); it
!= env
->env
.end(); ++it
)
837 const wxString line
= it
->first
+ wxS("=") + it
->second
;
839 // Include the trailing NUL which will always terminate the
840 // buffer returned by t_str().
841 const size_t len
= line
.length() + 1;
843 wxTmemcpy(p
, line
.t_str(), len
);
848 // And another NUL to terminate the list of NUL-terminated strings.
853 bool ok
= ::CreateProcess
855 // WinCE requires appname to be non null
856 // Win32 allows for null
859 moduleName
.wx_str(),// application name
861 arguments
.wx_str(), // arguments
863 NULL
, // application name (use only cmd line)
865 command
.wx_str(), // full command line
867 NULL
, // security attributes: defaults for both
868 NULL
, // the process and its main thread
869 redirect
, // inherit handles if we use pipes
870 dwFlags
, // process creation flags
871 envBuffer
.data(), // environment (may be NULL which is fine)
872 useCwd
// initial working directory
873 ? const_cast<wxChar
*>(env
->cwd
.wx_str())
874 : NULL
, // (or use the same)
875 &si
, // startup info (unused here)
879 #if wxUSE_STREAMS && !defined(__WXWINCE__)
880 // we can close the pipe ends used by child anyhow
883 ::CloseHandle(pipeIn
.Detach(wxPipe::Read
));
884 ::CloseHandle(pipeOut
.Detach(wxPipe::Write
));
885 ::CloseHandle(pipeErr
.Detach(wxPipe::Write
));
887 #endif // wxUSE_STREAMS
891 #if wxUSE_STREAMS && !defined(__WXWINCE__)
892 // close the other handles too
895 ::CloseHandle(pipeOut
.Detach(wxPipe::Read
));
896 ::CloseHandle(pipeErr
.Detach(wxPipe::Read
));
898 #endif // wxUSE_STREAMS
900 wxLogSysError(_("Execution of command '%s' failed"), command
.c_str());
902 return flags
& wxEXEC_SYNC
? -1 : 0;
905 #if wxUSE_STREAMS && !defined(__WXWINCE__)
906 // the input buffer bufOut is connected to stdout, this is why it is
907 // called bufOut and not bufIn
908 wxStreamTempInputBuffer bufOut
,
913 // We can now initialize the wxStreams
915 outStream
= new wxPipeInputStream(pipeOut
.Detach(wxPipe::Read
));
917 errStream
= new wxPipeInputStream(pipeErr
.Detach(wxPipe::Read
));
919 inStream
= new wxPipeOutputStream(hpipeStdinWrite
);
921 handler
->SetPipeStreams(outStream
, inStream
, errStream
);
923 bufOut
.Init(outStream
);
924 bufErr
.Init(errStream
);
926 #endif // wxUSE_STREAMS
928 // create a hidden window to receive notification about process
930 HWND hwnd
= wxCreateHiddenWindow
932 &gs_classForHiddenWindow
,
933 wxMSWEXEC_WNDCLASSNAME
,
934 (WNDPROC
)wxExecuteWindowCbk
937 wxASSERT_MSG( hwnd
, wxT("can't create a hidden window for wxExecute") );
940 wxExecuteData
*data
= new wxExecuteData
;
941 data
->hProcess
= pi
.hProcess
;
942 data
->dwProcessId
= pi
.dwProcessId
;
944 data
->state
= (flags
& wxEXEC_SYNC
) != 0;
945 if ( flags
& wxEXEC_SYNC
)
947 // handler may be !NULL for capturing program output, but we don't use
948 // it wxExecuteData struct in this case
949 data
->handler
= NULL
;
953 // may be NULL or not
954 data
->handler
= handler
;
957 handler
->SetPid(pi
.dwProcessId
);
961 HANDLE hThread
= ::CreateThread(NULL
,
968 // resume process we created now - whether the thread creation succeeded or
970 if ( ::ResumeThread(pi
.hThread
) == (DWORD
)-1 )
972 // ignore it - what can we do?
973 wxLogLastError(wxT("ResumeThread in wxExecute"));
976 // close unneeded handle
977 if ( !::CloseHandle(pi
.hThread
) )
979 wxLogLastError(wxT("CloseHandle(hThread)"));
984 wxLogLastError(wxT("CreateThread in wxExecute"));
989 // the process still started up successfully...
990 return pi
.dwProcessId
;
993 gs_asyncThreads
.push_back(hThread
);
995 #if wxUSE_IPC && !defined(__WXWINCE__)
996 // second part of DDE hack: now establish the DDE conversation with the
997 // just launched process
998 if ( !ddeServer
.empty() )
1002 // give the process the time to init itself
1004 // we use a very big timeout hoping that WaitForInputIdle() will return
1005 // much sooner, but not INFINITE just in case the process hangs
1006 // completely - like this we will regain control sooner or later
1007 switch ( ::WaitForInputIdle(pi
.hProcess
, 10000 /* 10 seconds */) )
1010 wxFAIL_MSG( wxT("unexpected WaitForInputIdle() return code") );
1014 wxLogLastError(wxT("WaitForInputIdle() in wxExecute"));
1017 wxLogDebug(wxT("Timeout too small in WaitForInputIdle"));
1023 // ok, process ready to accept DDE requests
1024 ok
= wxExecuteDDE(ddeServer
, ddeTopic
, ddeCommand
);
1029 wxLogDebug(wxT("Failed to send DDE request to the process \"%s\"."),
1035 if ( !(flags
& wxEXEC_SYNC
) )
1037 // clean up will be done when the process terminates
1040 return pi
.dwProcessId
;
1043 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
1044 wxCHECK_MSG( traits
, -1, wxT("no wxAppTraits in wxExecute()?") );
1046 void *cookie
= NULL
;
1047 if ( !(flags
& wxEXEC_NODISABLE
) )
1049 // disable all app windows while waiting for the child process to finish
1050 cookie
= traits
->BeforeChildWaitLoop();
1053 // wait until the child process terminates
1054 while ( data
->state
)
1056 #if wxUSE_STREAMS && !defined(__WXWINCE__)
1057 if ( !bufOut
.Update() && !bufErr
.Update() )
1058 #endif // wxUSE_STREAMS
1060 // don't eat 100% of the CPU -- ugly but anything else requires
1061 // real async IO which we don't have for the moment
1065 // we must always process messages for our hidden window or we'd never
1066 // get wxWM_PROC_TERMINATED and so this loop would never terminate
1068 ::PeekMessage(&msg
, data
->hWnd
, 0, 0, PM_REMOVE
);
1070 // we may also need to process messages for all the other application
1072 if ( !(flags
& wxEXEC_NOEVENTS
) )
1074 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
1080 if ( !(flags
& wxEXEC_NODISABLE
) )
1082 // reenable disabled windows back
1083 traits
->AfterChildWaitLoop(cookie
);
1086 DWORD dwExitCode
= data
->dwExitCode
;
1089 // return the exit code
1093 template <typename CharType
>
1094 long wxExecuteImpl(CharType
**argv
, int flags
, wxProcess
*handler
,
1095 const wxExecuteEnv
*env
)
1098 command
.reserve(1024);
1108 // we need to quote empty arguments, otherwise they'd just
1114 // escape any quotes present in the string to avoid interfering
1115 // with the command line parsing in the child process
1116 arg
.Replace("\"", "\\\"", true /* replace all */);
1118 // and quote any arguments containing the spaces to prevent them from
1119 // being broken down
1120 quote
= arg
.find_first_of(" \t") != wxString::npos
;
1124 command
+= '\"' + arg
+ '\"';
1134 return wxExecute(command
, flags
, handler
, env
);
1137 long wxExecute(char **argv
, int flags
, wxProcess
*handler
,
1138 const wxExecuteEnv
*env
)
1140 return wxExecuteImpl(argv
, flags
, handler
, env
);
1145 long wxExecute(wchar_t **argv
, int flags
, wxProcess
*handler
,
1146 const wxExecuteEnv
*env
)
1148 return wxExecuteImpl(argv
, flags
, handler
, env
);
1151 #endif // wxUSE_UNICODE