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 // ----------------------------------------------------------------------------
206 // ----------------------------------------------------------------------------
208 class wxPipeInputStream
: public wxInputStream
211 wxPipeInputStream(HANDLE hInput
);
212 virtual ~wxPipeInputStream();
214 // returns true if the pipe is still opened
215 bool IsOpened() const { return m_hInput
!= INVALID_HANDLE_VALUE
; }
217 // returns true if there is any data to be read from the pipe
218 virtual bool CanRead() const;
221 size_t OnSysRead(void *buffer
, size_t len
);
226 wxDECLARE_NO_COPY_CLASS(wxPipeInputStream
);
229 class wxPipeOutputStream
: public wxOutputStream
232 wxPipeOutputStream(HANDLE hOutput
);
233 virtual ~wxPipeOutputStream() { Close(); }
237 size_t OnSysWrite(const void *buffer
, size_t len
);
242 wxDECLARE_NO_COPY_CLASS(wxPipeOutputStream
);
245 // define this to let wxexec.cpp know that we know what we're doing
246 #define _WX_USED_BY_WXEXECUTE_
247 #include "../common/execcmn.cpp"
249 // ----------------------------------------------------------------------------
250 // wxPipe represents a Win32 anonymous pipe
251 // ----------------------------------------------------------------------------
256 // the symbolic names for the pipe ends
263 // default ctor doesn't do anything
264 wxPipe() { m_handles
[Read
] = m_handles
[Write
] = INVALID_HANDLE_VALUE
; }
266 // create the pipe, return true if ok, false on error
269 // default secutiry attributes
270 SECURITY_ATTRIBUTES security
;
272 security
.nLength
= sizeof(security
);
273 security
.lpSecurityDescriptor
= NULL
;
274 security
.bInheritHandle
= TRUE
; // to pass it to the child
276 if ( !::CreatePipe(&m_handles
[0], &m_handles
[1], &security
, 0) )
278 wxLogSysError(_("Failed to create an anonymous pipe"));
286 // return true if we were created successfully
287 bool IsOk() const { return m_handles
[Read
] != INVALID_HANDLE_VALUE
; }
289 // return the descriptor for one of the pipe ends
290 HANDLE
operator[](Direction which
) const { return m_handles
[which
]; }
292 // detach a descriptor, meaning that the pipe dtor won't close it, and
294 HANDLE
Detach(Direction which
)
296 HANDLE handle
= m_handles
[which
];
297 m_handles
[which
] = INVALID_HANDLE_VALUE
;
302 // close the pipe descriptors
305 for ( size_t n
= 0; n
< WXSIZEOF(m_handles
); n
++ )
307 if ( m_handles
[n
] != INVALID_HANDLE_VALUE
)
309 ::CloseHandle(m_handles
[n
]);
310 m_handles
[n
] = INVALID_HANDLE_VALUE
;
315 // dtor closes the pipe descriptors
316 ~wxPipe() { Close(); }
322 #endif // wxUSE_STREAMS
324 // ============================================================================
326 // ============================================================================
328 // ----------------------------------------------------------------------------
329 // process termination detecting support
330 // ----------------------------------------------------------------------------
332 // thread function for the thread monitoring the process termination
333 static DWORD __stdcall
wxExecuteThread(void *arg
)
335 wxExecuteData
* const data
= (wxExecuteData
*)arg
;
337 // create the shutdown event if we're the first thread starting to wait
338 if ( !gs_heventShutdown
)
340 // create a manual initially non-signalled event object
341 gs_heventShutdown
= ::CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
342 if ( !gs_heventShutdown
)
344 wxLogDebug(wxT("CreateEvent() in wxExecuteThread failed"));
348 HANDLE handles
[2] = { data
->hProcess
, gs_heventShutdown
};
349 switch ( ::WaitForMultipleObjects(2, handles
, FALSE
, INFINITE
) )
352 // process terminated, get its exit code
353 if ( !::GetExitCodeProcess(data
->hProcess
, &data
->dwExitCode
) )
355 wxLogLastError(wxT("GetExitCodeProcess"));
358 wxASSERT_MSG( data
->dwExitCode
!= STILL_ACTIVE
,
359 wxT("process should have terminated") );
361 // send a message indicating process termination to the window
362 ::SendMessage(data
->hWnd
, wxWM_PROC_TERMINATED
, 0, (LPARAM
)data
);
365 case WAIT_OBJECT_0
+ 1:
366 // we're shutting down but the process is still running -- leave it
367 // run but clean up the associated data
372 //else: exiting while synchronously executing process is still
373 // running? this shouldn't happen...
377 wxLogDebug(wxT("Waiting for the process termination failed!"));
383 // window procedure of a hidden window which is created just to receive
384 // the notification message when a process exits
385 LRESULT APIENTRY _EXPORT
wxExecuteWindowCbk(HWND hWnd
, UINT message
,
386 WPARAM wParam
, LPARAM lParam
)
388 if ( message
== wxWM_PROC_TERMINATED
)
390 DestroyWindow(hWnd
); // we don't need it any more
392 wxExecuteData
* const data
= (wxExecuteData
*)lParam
;
395 data
->handler
->OnTerminate((int)data
->dwProcessId
,
396 (int)data
->dwExitCode
);
401 // we're executing synchronously, tell the waiting thread
402 // that the process finished
407 // asynchronous execution - we should do the clean up
415 return ::DefWindowProc(hWnd
, message
, wParam
, lParam
);
419 // ============================================================================
420 // implementation of IO redirection support classes
421 // ============================================================================
423 #if wxUSE_STREAMS && !defined(__WXWINCE__)
425 // ----------------------------------------------------------------------------
426 // wxPipeInputStreams
427 // ----------------------------------------------------------------------------
429 wxPipeInputStream::wxPipeInputStream(HANDLE hInput
)
434 wxPipeInputStream::~wxPipeInputStream()
436 if ( m_hInput
!= INVALID_HANDLE_VALUE
)
437 ::CloseHandle(m_hInput
);
440 bool wxPipeInputStream::CanRead() const
442 // we can read if there's something in the put back buffer
443 // even pipe is closed
444 if ( m_wbacksize
> m_wbackcur
)
447 wxPipeInputStream
* const self
= wxConstCast(this, wxPipeInputStream
);
451 // set back to mark Eof as it may have been unset by Ungetch()
452 self
->m_lasterror
= wxSTREAM_EOF
;
458 // function name is misleading, it works with anon pipes as well
459 DWORD rc
= ::PeekNamedPipe
462 NULL
, 0, // ptr to buffer and its size
463 NULL
, // [out] bytes read
464 &nAvailable
, // [out] bytes available
465 NULL
// [out] bytes left
470 if ( ::GetLastError() != ERROR_BROKEN_PIPE
)
473 wxLogLastError(wxT("PeekNamedPipe"));
476 // don't try to continue reading from a pipe if an error occurred or if
477 // it had been closed
478 ::CloseHandle(m_hInput
);
480 self
->m_hInput
= INVALID_HANDLE_VALUE
;
481 self
->m_lasterror
= wxSTREAM_EOF
;
486 return nAvailable
!= 0;
489 size_t wxPipeInputStream::OnSysRead(void *buffer
, size_t len
)
493 m_lasterror
= wxSTREAM_EOF
;
499 if ( !::ReadFile(m_hInput
, buffer
, len
, &bytesRead
, NULL
) )
501 m_lasterror
= ::GetLastError() == ERROR_BROKEN_PIPE
503 : wxSTREAM_READ_ERROR
;
506 // bytesRead is set to 0, as desired, if an error occurred
510 // ----------------------------------------------------------------------------
511 // wxPipeOutputStream
512 // ----------------------------------------------------------------------------
514 wxPipeOutputStream::wxPipeOutputStream(HANDLE hOutput
)
518 // unblock the pipe to prevent deadlocks when we're writing to the pipe
519 // from which the child process can't read because it is writing in its own
521 DWORD mode
= PIPE_READMODE_BYTE
| PIPE_NOWAIT
;
522 if ( !::SetNamedPipeHandleState
526 NULL
, // collection count (we don't set it)
527 NULL
// timeout (we don't set it neither)
530 wxLogLastError(wxT("SetNamedPipeHandleState(PIPE_NOWAIT)"));
534 bool wxPipeOutputStream::Close()
536 return ::CloseHandle(m_hOutput
) != 0;
540 size_t wxPipeOutputStream::OnSysWrite(const void *buffer
, size_t len
)
542 m_lasterror
= wxSTREAM_NO_ERROR
;
544 DWORD totalWritten
= 0;
548 if ( !::WriteFile(m_hOutput
, buffer
, len
, &chunkWritten
, NULL
) )
550 m_lasterror
= ::GetLastError() == ERROR_BROKEN_PIPE
552 : wxSTREAM_WRITE_ERROR
;
559 buffer
= (char *)buffer
+ chunkWritten
;
560 totalWritten
+= chunkWritten
;
567 #endif // wxUSE_STREAMS
569 // ============================================================================
570 // wxExecute functions family
571 // ============================================================================
575 // connect to the given server via DDE and ask it to execute the command
577 wxExecuteDDE(const wxString
& ddeServer
,
578 const wxString
& ddeTopic
,
579 const wxString
& ddeCommand
)
581 bool ok
wxDUMMY_INITIALIZE(false);
585 conn
= client
.MakeConnection(wxEmptyString
, ddeServer
, ddeTopic
);
590 else // connected to DDE server
592 // the added complication here is that although most programs use
593 // XTYP_EXECUTE for their DDE API, some important ones -- like Word
594 // and other MS stuff - use XTYP_REQUEST!
596 // moreover, anotheri mportant program (IE) understands both but
597 // returns an error from Execute() so we must try Request() first
598 // to avoid doing it twice
600 // we're prepared for this one to fail, so don't show errors
603 ok
= conn
->Request(ddeCommand
) != NULL
;
608 // now try execute -- but show the errors
609 ok
= conn
->Execute(ddeCommand
);
618 long wxExecute(const wxString
& cmd
, int flags
, wxProcess
*handler
,
619 const wxExecuteEnv
*env
)
621 wxCHECK_MSG( !cmd
.empty(), 0, wxT("empty command in wxExecute") );
624 // for many reasons, the code below breaks down if it's called from another
625 // thread -- this could be fixed, but as Unix versions don't support this
626 // neither I don't want to waste time on this now
627 wxASSERT_MSG( wxThread::IsMain(),
628 wxT("wxExecute() can be called only from the main thread") );
629 #endif // wxUSE_THREADS
634 // DDE hack: this is really not pretty, but we need to allow this for
635 // transparent handling of DDE servers in wxMimeTypesManager. Usually it
636 // returns the command which should be run to view/open/... a file of the
637 // given type. Sometimes, however, this command just launches the server
638 // and an additional DDE request must be made to really open the file. To
639 // keep all this well hidden from the application, we allow a special form
640 // of command: WX_DDE#<command>#DDE_SERVER#DDE_TOPIC#DDE_COMMAND in which
641 // case we execute just <command> and process the rest below
642 wxString ddeServer
, ddeTopic
, ddeCommand
;
643 static const size_t lenDdePrefix
= 7; // strlen("WX_DDE:")
644 if ( cmd
.Left(lenDdePrefix
) == wxT("WX_DDE#") )
646 // speed up the concatenations below
647 ddeServer
.reserve(256);
648 ddeTopic
.reserve(256);
649 ddeCommand
.reserve(256);
651 const wxChar
*p
= cmd
.c_str() + 7;
652 while ( *p
&& *p
!= wxT('#') )
664 wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute"));
667 while ( *p
&& *p
!= wxT('#') )
679 wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute"));
682 while ( *p
&& *p
!= wxT('#') )
694 wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute"));
702 // if we want to just launch the program and not wait for its
703 // termination, try to execute DDE command right now, it can succeed if
704 // the process is already running - but as it fails if it's not
705 // running, suppress any errors it might generate
706 if ( !(flags
& wxEXEC_SYNC
) )
709 if ( wxExecuteDDE(ddeServer
, ddeTopic
, ddeCommand
) )
711 // a dummy PID - this is a hack, of course, but it's well worth
712 // it as we don't open a new server each time we're called
713 // which would be quite bad
725 // the IO redirection is only supported with wxUSE_STREAMS
726 BOOL redirect
= FALSE
;
728 #if wxUSE_STREAMS && !defined(__WXWINCE__)
729 wxPipe pipeIn
, pipeOut
, pipeErr
;
731 // we'll save here the copy of pipeIn[Write]
732 HANDLE hpipeStdinWrite
= INVALID_HANDLE_VALUE
;
734 // open the pipes to which child process IO will be redirected if needed
735 if ( handler
&& handler
->IsRedirected() )
737 // create pipes for redirecting stdin, stdout and stderr
738 if ( !pipeIn
.Create() || !pipeOut
.Create() || !pipeErr
.Create() )
740 wxLogSysError(_("Failed to redirect the child process IO"));
742 // indicate failure: we need to return different error code
743 // depending on the sync flag
744 return flags
& wxEXEC_SYNC
? -1 : 0;
749 #endif // wxUSE_STREAMS
751 // create the process
756 #if wxUSE_STREAMS && !defined(__WXWINCE__)
759 si
.dwFlags
= STARTF_USESTDHANDLES
;
761 si
.hStdInput
= pipeIn
[wxPipe::Read
];
762 si
.hStdOutput
= pipeOut
[wxPipe::Write
];
763 si
.hStdError
= pipeErr
[wxPipe::Write
];
765 // we must duplicate the handle to the write side of stdin pipe to make
766 // it non inheritable: indeed, we must close the writing end of pipeIn
767 // before launching the child process as otherwise this handle will be
768 // inherited by the child which will never close it and so the pipe
769 // will never be closed and the child will be left stuck in ReadFile()
770 HANDLE pipeInWrite
= pipeIn
.Detach(wxPipe::Write
);
771 if ( !::DuplicateHandle
773 ::GetCurrentProcess(),
775 ::GetCurrentProcess(),
777 0, // desired access: unused here
778 FALSE
, // not inherited
779 DUPLICATE_SAME_ACCESS
// same access as for src handle
782 wxLogLastError(wxT("DuplicateHandle"));
785 ::CloseHandle(pipeInWrite
);
787 #endif // wxUSE_STREAMS
789 // The default logic for showing the console is to show it only if the IO
790 // is not redirected however wxEXEC_{SHOW,HIDE}_CONSOLE flags can be
791 // explicitly specified to change it.
792 if ( (flags
& wxEXEC_HIDE_CONSOLE
) ||
793 (redirect
&& !(flags
& wxEXEC_SHOW_CONSOLE
)) )
795 si
.dwFlags
|= STARTF_USESHOWWINDOW
;
796 si
.wShowWindow
= SW_HIDE
;
800 PROCESS_INFORMATION pi
;
801 DWORD dwFlags
= CREATE_SUSPENDED
;
804 if ( (flags
& wxEXEC_MAKE_GROUP_LEADER
) &&
805 (wxGetOsVersion() == wxOS_WINDOWS_NT
) )
806 dwFlags
|= CREATE_NEW_PROCESS_GROUP
;
808 dwFlags
|= CREATE_DEFAULT_ERROR_MODE
;
810 // we are assuming commands without spaces for now
811 wxString moduleName
= command
.BeforeFirst(wxT(' '));
812 wxString arguments
= command
.AfterFirst(wxT(' '));
815 wxWxCharBuffer envBuffer
;
819 useCwd
= !env
->cwd
.empty();
821 // Translate environment variable map into NUL-terminated list of
822 // NUL-terminated strings.
823 if ( !env
->env
.empty() )
826 // Environment variables can contain non-ASCII characters. We could
827 // check for it and not use this flag if everything is really ASCII
828 // only but there doesn't seem to be any reason to do it so just
829 // assume Unicode by default.
830 dwFlags
|= CREATE_UNICODE_ENVIRONMENT
;
831 #endif // wxUSE_UNICODE
833 wxEnvVariableHashMap::const_iterator it
;
835 size_t envSz
= 1; // ending '\0'
836 for ( it
= env
->env
.begin(); it
!= env
->env
.end(); ++it
)
838 // Add size of env variable name and value, and '=' char and
840 envSz
+= it
->first
.length() + it
->second
.length() + 2;
843 envBuffer
.extend(envSz
);
845 wxChar
*p
= envBuffer
.data();
846 for ( it
= env
->env
.begin(); it
!= env
->env
.end(); ++it
)
848 const wxString line
= it
->first
+ wxS("=") + it
->second
;
850 // Include the trailing NUL which will always terminate the
851 // buffer returned by t_str().
852 const size_t len
= line
.length() + 1;
854 wxTmemcpy(p
, line
.t_str(), len
);
859 // And another NUL to terminate the list of NUL-terminated strings.
864 // Translate wxWidgets priority to Windows conventions.
867 unsigned prio
= handler
->GetPriority();
869 dwFlags
|= IDLE_PRIORITY_CLASS
;
870 else if ( prio
<= 40 )
871 dwFlags
|= BELOW_NORMAL_PRIORITY_CLASS
;
872 else if ( prio
<= 60 )
873 dwFlags
|= NORMAL_PRIORITY_CLASS
;
874 else if ( prio
<= 80 )
875 dwFlags
|= ABOVE_NORMAL_PRIORITY_CLASS
;
876 else if ( prio
<= 99 )
877 dwFlags
|= HIGH_PRIORITY_CLASS
;
878 else if ( prio
<= 100 )
879 dwFlags
|= REALTIME_PRIORITY_CLASS
;
882 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
883 dwFlags
|= NORMAL_PRIORITY_CLASS
;
887 bool ok
= ::CreateProcess
889 // WinCE requires appname to be non null
890 // Win32 allows for null
892 moduleName
.t_str(), // application name
893 wxMSW_CONV_LPTSTR(arguments
), // arguments
895 NULL
, // application name (use only cmd line)
896 wxMSW_CONV_LPTSTR(command
), // full command line
898 NULL
, // security attributes: defaults for both
899 NULL
, // the process and its main thread
900 redirect
, // inherit handles if we use pipes
901 dwFlags
, // process creation flags
902 envBuffer
.data(), // environment (may be NULL which is fine)
903 useCwd
// initial working directory
904 ? wxMSW_CONV_LPTSTR(env
->cwd
)
905 : NULL
, // (or use the same)
906 &si
, // startup info (unused here)
910 #if wxUSE_STREAMS && !defined(__WXWINCE__)
911 // we can close the pipe ends used by child anyhow
914 ::CloseHandle(pipeIn
.Detach(wxPipe::Read
));
915 ::CloseHandle(pipeOut
.Detach(wxPipe::Write
));
916 ::CloseHandle(pipeErr
.Detach(wxPipe::Write
));
918 #endif // wxUSE_STREAMS
922 #if wxUSE_STREAMS && !defined(__WXWINCE__)
923 // close the other handles too
926 ::CloseHandle(pipeOut
.Detach(wxPipe::Read
));
927 ::CloseHandle(pipeErr
.Detach(wxPipe::Read
));
929 #endif // wxUSE_STREAMS
931 wxLogSysError(_("Execution of command '%s' failed"), command
.c_str());
933 return flags
& wxEXEC_SYNC
? -1 : 0;
936 #if wxUSE_STREAMS && !defined(__WXWINCE__)
937 // the input buffer bufOut is connected to stdout, this is why it is
938 // called bufOut and not bufIn
939 wxStreamTempInputBuffer bufOut
,
944 // We can now initialize the wxStreams
946 outStream
= new wxPipeInputStream(pipeOut
.Detach(wxPipe::Read
));
948 errStream
= new wxPipeInputStream(pipeErr
.Detach(wxPipe::Read
));
950 inStream
= new wxPipeOutputStream(hpipeStdinWrite
);
952 handler
->SetPipeStreams(outStream
, inStream
, errStream
);
954 bufOut
.Init(outStream
);
955 bufErr
.Init(errStream
);
957 #endif // wxUSE_STREAMS
959 // create a hidden window to receive notification about process
961 HWND hwnd
= wxCreateHiddenWindow
963 &gs_classForHiddenWindow
,
964 wxMSWEXEC_WNDCLASSNAME
,
965 (WNDPROC
)wxExecuteWindowCbk
968 wxASSERT_MSG( hwnd
, wxT("can't create a hidden window for wxExecute") );
971 wxExecuteData
*data
= new wxExecuteData
;
972 data
->hProcess
= pi
.hProcess
;
973 data
->dwProcessId
= pi
.dwProcessId
;
975 data
->state
= (flags
& wxEXEC_SYNC
) != 0;
976 if ( flags
& wxEXEC_SYNC
)
978 // handler may be !NULL for capturing program output, but we don't use
979 // it wxExecuteData struct in this case
980 data
->handler
= NULL
;
984 // may be NULL or not
985 data
->handler
= handler
;
988 handler
->SetPid(pi
.dwProcessId
);
992 HANDLE hThread
= ::CreateThread(NULL
,
999 // resume process we created now - whether the thread creation succeeded or
1001 if ( ::ResumeThread(pi
.hThread
) == (DWORD
)-1 )
1003 // ignore it - what can we do?
1004 wxLogLastError(wxT("ResumeThread in wxExecute"));
1007 // close unneeded handle
1008 if ( !::CloseHandle(pi
.hThread
) )
1010 wxLogLastError(wxT("CloseHandle(hThread)"));
1015 wxLogLastError(wxT("CreateThread in wxExecute"));
1017 DestroyWindow(hwnd
);
1020 // the process still started up successfully...
1021 return pi
.dwProcessId
;
1024 gs_asyncThreads
.push_back(hThread
);
1026 #if wxUSE_IPC && !defined(__WXWINCE__)
1027 // second part of DDE hack: now establish the DDE conversation with the
1028 // just launched process
1029 if ( !ddeServer
.empty() )
1033 // give the process the time to init itself
1035 // we use a very big timeout hoping that WaitForInputIdle() will return
1036 // much sooner, but not INFINITE just in case the process hangs
1037 // completely - like this we will regain control sooner or later
1038 switch ( ::WaitForInputIdle(pi
.hProcess
, 10000 /* 10 seconds */) )
1041 wxFAIL_MSG( wxT("unexpected WaitForInputIdle() return code") );
1045 wxLogLastError(wxT("WaitForInputIdle() in wxExecute"));
1048 wxLogDebug(wxT("Timeout too small in WaitForInputIdle"));
1054 // ok, process ready to accept DDE requests
1055 ddeOK
= wxExecuteDDE(ddeServer
, ddeTopic
, ddeCommand
);
1060 wxLogDebug(wxT("Failed to send DDE request to the process \"%s\"."),
1066 if ( !(flags
& wxEXEC_SYNC
) )
1068 // clean up will be done when the process terminates
1071 return pi
.dwProcessId
;
1074 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
1075 wxCHECK_MSG( traits
, -1, wxT("no wxAppTraits in wxExecute()?") );
1077 void *cookie
= NULL
;
1078 if ( !(flags
& wxEXEC_NODISABLE
) )
1080 // disable all app windows while waiting for the child process to finish
1081 cookie
= traits
->BeforeChildWaitLoop();
1084 // wait until the child process terminates
1085 while ( data
->state
)
1087 #if wxUSE_STREAMS && !defined(__WXWINCE__)
1088 if ( !bufOut
.Update() && !bufErr
.Update() )
1089 #endif // wxUSE_STREAMS
1091 // don't eat 100% of the CPU -- ugly but anything else requires
1092 // real async IO which we don't have for the moment
1096 // we must always process messages for our hidden window or we'd never
1097 // get wxWM_PROC_TERMINATED and so this loop would never terminate
1099 ::PeekMessage(&msg
, data
->hWnd
, 0, 0, PM_REMOVE
);
1101 // we may also need to process messages for all the other application
1103 if ( !(flags
& wxEXEC_NOEVENTS
) )
1105 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
1111 if ( !(flags
& wxEXEC_NODISABLE
) )
1113 // reenable disabled windows back
1114 traits
->AfterChildWaitLoop(cookie
);
1117 DWORD dwExitCode
= data
->dwExitCode
;
1120 // return the exit code
1124 template <typename CharType
>
1125 long wxExecuteImpl(CharType
**argv
, int flags
, wxProcess
*handler
,
1126 const wxExecuteEnv
*env
)
1129 command
.reserve(1024);
1139 // we need to quote empty arguments, otherwise they'd just
1145 // escape any quotes present in the string to avoid interfering
1146 // with the command line parsing in the child process
1147 arg
.Replace("\"", "\\\"", true /* replace all */);
1149 // and quote any arguments containing the spaces to prevent them from
1150 // being broken down
1151 quote
= arg
.find_first_of(" \t") != wxString::npos
;
1155 command
+= '\"' + arg
+ '\"';
1165 return wxExecute(command
, flags
, handler
, env
);
1168 long wxExecute(char **argv
, int flags
, wxProcess
*handler
,
1169 const wxExecuteEnv
*env
)
1171 return wxExecuteImpl(argv
, flags
, handler
, env
);
1176 long wxExecute(wchar_t **argv
, int flags
, wxProcess
*handler
,
1177 const wxExecuteEnv
*env
)
1179 return wxExecuteImpl(argv
, flags
, handler
, env
);
1182 #endif // wxUSE_UNICODE