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"
34 #include "wx/stream.h"
35 #include "wx/process.h"
37 #include "wx/apptrait.h"
39 #include "wx/module.h"
41 #include "wx/msw/private.h"
45 #if !defined(__GNUWIN32__) && !defined(__SALFORDC__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
52 #if defined(__GNUWIN32__)
53 #include <sys/unistd.h>
57 #if !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
71 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
78 #include "wx/dde.h" // for WX_DDE hack in wxExecute
81 // implemented in utils.cpp
82 extern "C" WXDLLIMPEXP_BASE HWND
83 wxCreateHiddenWindow(LPCTSTR
*pclassname
, LPCTSTR classname
, WNDPROC wndproc
);
85 // ----------------------------------------------------------------------------
87 // ----------------------------------------------------------------------------
89 // this message is sent when the process we're waiting for terminates
90 #define wxWM_PROC_TERMINATED (WM_USER + 10000)
92 // ----------------------------------------------------------------------------
93 // this module globals
94 // ----------------------------------------------------------------------------
96 // we need to create a hidden window to receive the process termination
97 // notifications and for this we need a (Win) class name for it which we will
98 // register the first time it's needed
99 static const wxChar
*wxMSWEXEC_WNDCLASSNAME
= wxT("_wxExecute_Internal_Class");
100 static const wxChar
*gs_classForHiddenWindow
= NULL
;
102 // ----------------------------------------------------------------------------
104 // ----------------------------------------------------------------------------
106 // structure describing the process we're being waiting for
112 if ( !::CloseHandle(hProcess
) )
114 wxLogLastError(wxT("CloseHandle(hProcess)"));
118 HWND hWnd
; // window to send wxWM_PROC_TERMINATED to
119 HANDLE hProcess
; // handle of the process
120 DWORD dwProcessId
; // pid of the process
122 DWORD dwExitCode
; // the exit code of the process
123 bool state
; // set to false when the process finishes
126 class wxExecuteModule
: public wxModule
129 virtual bool OnInit() { return true; }
130 virtual void OnExit()
132 if ( *gs_classForHiddenWindow
)
134 if ( !::UnregisterClass(wxMSWEXEC_WNDCLASSNAME
, wxGetInstance()) )
136 wxLogLastError(_T("UnregisterClass(wxExecClass)"));
139 gs_classForHiddenWindow
= NULL
;
144 DECLARE_DYNAMIC_CLASS(wxExecuteModule
)
147 #if wxUSE_STREAMS && !defined(__WXWINCE__)
149 // ----------------------------------------------------------------------------
151 // ----------------------------------------------------------------------------
153 class wxPipeInputStream
: public wxInputStream
156 wxPipeInputStream(HANDLE hInput
);
157 virtual ~wxPipeInputStream();
159 // returns true if the pipe is still opened
160 bool IsOpened() const { return m_hInput
!= INVALID_HANDLE_VALUE
; }
162 // returns true if there is any data to be read from the pipe
163 virtual bool CanRead() const;
166 size_t OnSysRead(void *buffer
, size_t len
);
171 DECLARE_NO_COPY_CLASS(wxPipeInputStream
)
174 class wxPipeOutputStream
: public wxOutputStream
177 wxPipeOutputStream(HANDLE hOutput
);
178 virtual ~wxPipeOutputStream() { Close(); }
182 size_t OnSysWrite(const void *buffer
, size_t len
);
187 DECLARE_NO_COPY_CLASS(wxPipeOutputStream
)
190 // define this to let wxexec.cpp know that we know what we're doing
191 #define _WX_USED_BY_WXEXECUTE_
192 #include "../common/execcmn.cpp"
194 // ----------------------------------------------------------------------------
195 // wxPipe represents a Win32 anonymous pipe
196 // ----------------------------------------------------------------------------
201 // the symbolic names for the pipe ends
208 // default ctor doesn't do anything
209 wxPipe() { m_handles
[Read
] = m_handles
[Write
] = INVALID_HANDLE_VALUE
; }
211 // create the pipe, return true if ok, false on error
214 // default secutiry attributes
215 SECURITY_ATTRIBUTES security
;
217 security
.nLength
= sizeof(security
);
218 security
.lpSecurityDescriptor
= NULL
;
219 security
.bInheritHandle
= TRUE
; // to pass it to the child
221 if ( !::CreatePipe(&m_handles
[0], &m_handles
[1], &security
, 0) )
223 wxLogSysError(_("Failed to create an anonymous pipe"));
231 // return true if we were created successfully
232 bool IsOk() const { return m_handles
[Read
] != INVALID_HANDLE_VALUE
; }
234 // return the descriptor for one of the pipe ends
235 HANDLE
operator[](Direction which
) const { return m_handles
[which
]; }
237 // detach a descriptor, meaning that the pipe dtor won't close it, and
239 HANDLE
Detach(Direction which
)
241 HANDLE handle
= m_handles
[which
];
242 m_handles
[which
] = INVALID_HANDLE_VALUE
;
247 // close the pipe descriptors
250 for ( size_t n
= 0; n
< WXSIZEOF(m_handles
); n
++ )
252 if ( m_handles
[n
] != INVALID_HANDLE_VALUE
)
254 ::CloseHandle(m_handles
[n
]);
255 m_handles
[n
] = INVALID_HANDLE_VALUE
;
260 // dtor closes the pipe descriptors
261 ~wxPipe() { Close(); }
267 #endif // wxUSE_STREAMS
269 // ============================================================================
271 // ============================================================================
273 // ----------------------------------------------------------------------------
274 // process termination detecting support
275 // ----------------------------------------------------------------------------
277 // thread function for the thread monitoring the process termination
278 static DWORD __stdcall
wxExecuteThread(void *arg
)
280 wxExecuteData
* const data
= (wxExecuteData
*)arg
;
282 if ( ::WaitForSingleObject(data
->hProcess
, INFINITE
) != WAIT_OBJECT_0
)
284 wxLogDebug(_T("Waiting for the process termination failed!"));
288 if ( !::GetExitCodeProcess(data
->hProcess
, &data
->dwExitCode
) )
290 wxLogLastError(wxT("GetExitCodeProcess"));
293 wxASSERT_MSG( data
->dwExitCode
!= STILL_ACTIVE
,
294 wxT("process should have terminated") );
296 // send a message indicating process termination to the window
297 ::SendMessage(data
->hWnd
, wxWM_PROC_TERMINATED
, 0, (LPARAM
)data
);
302 // window procedure of a hidden window which is created just to receive
303 // the notification message when a process exits
304 LRESULT APIENTRY _EXPORT
wxExecuteWindowCbk(HWND hWnd
, UINT message
,
305 WPARAM wParam
, LPARAM lParam
)
307 if ( message
== wxWM_PROC_TERMINATED
)
309 DestroyWindow(hWnd
); // we don't need it any more
311 wxExecuteData
* const data
= (wxExecuteData
*)lParam
;
314 data
->handler
->OnTerminate((int)data
->dwProcessId
,
315 (int)data
->dwExitCode
);
320 // we're executing synchronously, tell the waiting thread
321 // that the process finished
326 // asynchronous execution - we should do the clean up
334 return ::DefWindowProc(hWnd
, message
, wParam
, lParam
);
338 // ============================================================================
339 // implementation of IO redirection support classes
340 // ============================================================================
342 #if wxUSE_STREAMS && !defined(__WXWINCE__)
344 // ----------------------------------------------------------------------------
345 // wxPipeInputStreams
346 // ----------------------------------------------------------------------------
348 wxPipeInputStream::wxPipeInputStream(HANDLE hInput
)
353 wxPipeInputStream::~wxPipeInputStream()
355 if ( m_hInput
!= INVALID_HANDLE_VALUE
)
356 ::CloseHandle(m_hInput
);
359 bool wxPipeInputStream::CanRead() const
366 // function name is misleading, it works with anon pipes as well
367 DWORD rc
= ::PeekNamedPipe
370 NULL
, 0, // ptr to buffer and its size
371 NULL
, // [out] bytes read
372 &nAvailable
, // [out] bytes available
373 NULL
// [out] bytes left
378 if ( ::GetLastError() != ERROR_BROKEN_PIPE
)
381 wxLogLastError(_T("PeekNamedPipe"));
384 // don't try to continue reading from a pipe if an error occurred or if
385 // it had been closed
386 ::CloseHandle(m_hInput
);
388 wxPipeInputStream
*self
= wxConstCast(this, wxPipeInputStream
);
390 self
->m_hInput
= INVALID_HANDLE_VALUE
;
391 self
->m_lasterror
= wxSTREAM_EOF
;
396 return nAvailable
!= 0;
399 size_t wxPipeInputStream::OnSysRead(void *buffer
, size_t len
)
403 m_lasterror
= wxSTREAM_EOF
;
409 if ( !::ReadFile(m_hInput
, buffer
, len
, &bytesRead
, NULL
) )
411 m_lasterror
= ::GetLastError() == ERROR_BROKEN_PIPE
413 : wxSTREAM_READ_ERROR
;
416 // bytesRead is set to 0, as desired, if an error occurred
420 // ----------------------------------------------------------------------------
421 // wxPipeOutputStream
422 // ----------------------------------------------------------------------------
424 wxPipeOutputStream::wxPipeOutputStream(HANDLE hOutput
)
428 // unblock the pipe to prevent deadlocks when we're writing to the pipe
429 // from which the child process can't read because it is writing in its own
431 DWORD mode
= PIPE_READMODE_BYTE
| PIPE_NOWAIT
;
432 if ( !::SetNamedPipeHandleState
436 NULL
, // collection count (we don't set it)
437 NULL
// timeout (we don't set it neither)
440 wxLogLastError(_T("SetNamedPipeHandleState(PIPE_NOWAIT)"));
444 bool wxPipeOutputStream::Close()
446 return ::CloseHandle(m_hOutput
) != 0;
450 size_t wxPipeOutputStream::OnSysWrite(const void *buffer
, size_t len
)
452 m_lasterror
= wxSTREAM_NO_ERROR
;
454 DWORD totalWritten
= 0;
458 if ( !::WriteFile(m_hOutput
, buffer
, len
, &chunkWritten
, NULL
) )
460 m_lasterror
= ::GetLastError() == ERROR_BROKEN_PIPE
462 : wxSTREAM_WRITE_ERROR
;
469 buffer
= (char *)buffer
+ chunkWritten
;
470 totalWritten
+= chunkWritten
;
477 #endif // wxUSE_STREAMS
479 // ============================================================================
480 // wxExecute functions family
481 // ============================================================================
485 // connect to the given server via DDE and ask it to execute the command
487 wxExecuteDDE(const wxString
& ddeServer
,
488 const wxString
& ddeTopic
,
489 const wxString
& ddeCommand
)
491 bool ok
wxDUMMY_INITIALIZE(false);
495 conn
= client
.MakeConnection(wxEmptyString
, ddeServer
, ddeTopic
);
500 else // connected to DDE server
502 // the added complication here is that although most programs use
503 // XTYP_EXECUTE for their DDE API, some important ones -- like Word
504 // and other MS stuff - use XTYP_REQUEST!
506 // moreover, anotheri mportant program (IE) understands both but
507 // returns an error from Execute() so we must try Request() first
508 // to avoid doing it twice
510 // we're prepared for this one to fail, so don't show errors
513 ok
= conn
->Request(ddeCommand
) != NULL
;
518 // now try execute -- but show the errors
519 ok
= conn
->Execute(ddeCommand
);
528 long wxExecute(const wxString
& cmd
, int flags
, wxProcess
*handler
)
530 wxCHECK_MSG( !cmd
.empty(), 0, wxT("empty command in wxExecute") );
533 // for many reasons, the code below breaks down if it's called from another
534 // thread -- this could be fixed, but as Unix versions don't support this
535 // neither I don't want to waste time on this now
536 wxASSERT_MSG( wxThread::IsMain(),
537 _T("wxExecute() can be called only from the main thread") );
538 #endif // wxUSE_THREADS
543 // DDE hack: this is really not pretty, but we need to allow this for
544 // transparent handling of DDE servers in wxMimeTypesManager. Usually it
545 // returns the command which should be run to view/open/... a file of the
546 // given type. Sometimes, however, this command just launches the server
547 // and an additional DDE request must be made to really open the file. To
548 // keep all this well hidden from the application, we allow a special form
549 // of command: WX_DDE#<command>#DDE_SERVER#DDE_TOPIC#DDE_COMMAND in which
550 // case we execute just <command> and process the rest below
551 wxString ddeServer
, ddeTopic
, ddeCommand
;
552 static const size_t lenDdePrefix
= 7; // strlen("WX_DDE:")
553 if ( cmd
.Left(lenDdePrefix
) == _T("WX_DDE#") )
555 // speed up the concatenations below
556 ddeServer
.reserve(256);
557 ddeTopic
.reserve(256);
558 ddeCommand
.reserve(256);
560 const wxChar
*p
= cmd
.c_str() + 7;
561 while ( *p
&& *p
!= _T('#') )
573 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
576 while ( *p
&& *p
!= _T('#') )
588 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
591 while ( *p
&& *p
!= _T('#') )
603 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
611 // if we want to just launch the program and not wait for its
612 // termination, try to execute DDE command right now, it can succeed if
613 // the process is already running - but as it fails if it's not
614 // running, suppress any errors it might generate
615 if ( !(flags
& wxEXEC_SYNC
) )
618 if ( wxExecuteDDE(ddeServer
, ddeTopic
, ddeCommand
) )
620 // a dummy PID - this is a hack, of course, but it's well worth
621 // it as we don't open a new server each time we're called
622 // which would be quite bad
634 // the IO redirection is only supported with wxUSE_STREAMS
635 BOOL redirect
= FALSE
;
637 #if wxUSE_STREAMS && !defined(__WXWINCE__)
638 wxPipe pipeIn
, pipeOut
, pipeErr
;
640 // we'll save here the copy of pipeIn[Write]
641 HANDLE hpipeStdinWrite
= INVALID_HANDLE_VALUE
;
643 // open the pipes to which child process IO will be redirected if needed
644 if ( handler
&& handler
->IsRedirected() )
646 // create pipes for redirecting stdin, stdout and stderr
647 if ( !pipeIn
.Create() || !pipeOut
.Create() || !pipeErr
.Create() )
649 wxLogSysError(_("Failed to redirect the child process IO"));
651 // indicate failure: we need to return different error code
652 // depending on the sync flag
653 return flags
& wxEXEC_SYNC
? -1 : 0;
658 #endif // wxUSE_STREAMS
660 // create the process
665 #if wxUSE_STREAMS && !defined(__WXWINCE__)
668 si
.dwFlags
= STARTF_USESTDHANDLES
;
670 si
.hStdInput
= pipeIn
[wxPipe::Read
];
671 si
.hStdOutput
= pipeOut
[wxPipe::Write
];
672 si
.hStdError
= pipeErr
[wxPipe::Write
];
674 // when the std IO is redirected, we don't show the (console) process
675 // window by default, but this can be overridden by the caller by
676 // specifying wxEXEC_NOHIDE flag
677 if ( !(flags
& wxEXEC_NOHIDE
) )
679 si
.dwFlags
|= STARTF_USESHOWWINDOW
;
680 si
.wShowWindow
= SW_HIDE
;
683 // we must duplicate the handle to the write side of stdin pipe to make
684 // it non inheritable: indeed, we must close the writing end of pipeIn
685 // before launching the child process as otherwise this handle will be
686 // inherited by the child which will never close it and so the pipe
687 // will never be closed and the child will be left stuck in ReadFile()
688 HANDLE pipeInWrite
= pipeIn
.Detach(wxPipe::Write
);
689 if ( !::DuplicateHandle
691 ::GetCurrentProcess(),
693 ::GetCurrentProcess(),
695 0, // desired access: unused here
696 FALSE
, // not inherited
697 DUPLICATE_SAME_ACCESS
// same access as for src handle
700 wxLogLastError(_T("DuplicateHandle"));
703 ::CloseHandle(pipeInWrite
);
705 #endif // wxUSE_STREAMS
707 PROCESS_INFORMATION pi
;
708 DWORD dwFlags
= CREATE_SUSPENDED
;
711 dwFlags
|= CREATE_DEFAULT_ERROR_MODE
;
713 // we are assuming commands without spaces for now
714 wxString moduleName
= command
.BeforeFirst(wxT(' '));
715 wxString arguments
= command
.AfterFirst(wxT(' '));
718 bool ok
= ::CreateProcess
720 // WinCE requires appname to be non null
721 // Win32 allows for null
724 moduleName
.c_str(), // application name
726 arguments
.c_str(), // arguments
728 NULL
, // application name (use only cmd line)
730 command
.c_str(), // full command line
732 NULL
, // security attributes: defaults for both
733 NULL
, // the process and its main thread
734 redirect
, // inherit handles if we use pipes
735 dwFlags
, // process creation flags
736 NULL
, // environment (use the same)
737 NULL
, // current directory (use the same)
738 &si
, // startup info (unused here)
742 #if wxUSE_STREAMS && !defined(__WXWINCE__)
743 // we can close the pipe ends used by child anyhow
746 ::CloseHandle(pipeIn
.Detach(wxPipe::Read
));
747 ::CloseHandle(pipeOut
.Detach(wxPipe::Write
));
748 ::CloseHandle(pipeErr
.Detach(wxPipe::Write
));
750 #endif // wxUSE_STREAMS
754 #if wxUSE_STREAMS && !defined(__WXWINCE__)
755 // close the other handles too
758 ::CloseHandle(pipeOut
.Detach(wxPipe::Read
));
759 ::CloseHandle(pipeErr
.Detach(wxPipe::Read
));
761 #endif // wxUSE_STREAMS
763 wxLogSysError(_("Execution of command '%s' failed"), command
.c_str());
765 return flags
& wxEXEC_SYNC
? -1 : 0;
768 #if wxUSE_STREAMS && !defined(__WXWINCE__)
769 // the input buffer bufOut is connected to stdout, this is why it is
770 // called bufOut and not bufIn
771 wxStreamTempInputBuffer bufOut
,
776 // We can now initialize the wxStreams
778 outStream
= new wxPipeInputStream(pipeOut
.Detach(wxPipe::Read
));
780 errStream
= new wxPipeInputStream(pipeErr
.Detach(wxPipe::Read
));
782 inStream
= new wxPipeOutputStream(hpipeStdinWrite
);
784 handler
->SetPipeStreams(outStream
, inStream
, errStream
);
786 bufOut
.Init(outStream
);
787 bufErr
.Init(errStream
);
789 #endif // wxUSE_STREAMS
791 // create a hidden window to receive notification about process
793 HWND hwnd
= wxCreateHiddenWindow
795 &gs_classForHiddenWindow
,
796 wxMSWEXEC_WNDCLASSNAME
,
797 (WNDPROC
)wxExecuteWindowCbk
800 wxASSERT_MSG( hwnd
, wxT("can't create a hidden window for wxExecute") );
803 wxExecuteData
*data
= new wxExecuteData
;
804 data
->hProcess
= pi
.hProcess
;
805 data
->dwProcessId
= pi
.dwProcessId
;
807 data
->state
= (flags
& wxEXEC_SYNC
) != 0;
808 if ( flags
& wxEXEC_SYNC
)
810 // handler may be !NULL for capturing program output, but we don't use
811 // it wxExecuteData struct in this case
812 data
->handler
= NULL
;
816 // may be NULL or not
817 data
->handler
= handler
;
821 HANDLE hThread
= ::CreateThread(NULL
,
828 // resume process we created now - whether the thread creation succeeded or
830 if ( ::ResumeThread(pi
.hThread
) == (DWORD
)-1 )
832 // ignore it - what can we do?
833 wxLogLastError(wxT("ResumeThread in wxExecute"));
836 // close unneeded handle
837 if ( !::CloseHandle(pi
.hThread
) )
838 wxLogLastError(wxT("CloseHandle(hThread)"));
842 wxLogLastError(wxT("CreateThread in wxExecute"));
847 // the process still started up successfully...
848 return pi
.dwProcessId
;
851 ::CloseHandle(hThread
);
853 #if wxUSE_IPC && !defined(__WXWINCE__)
854 // second part of DDE hack: now establish the DDE conversation with the
855 // just launched process
856 if ( !ddeServer
.empty() )
860 // give the process the time to init itself
862 // we use a very big timeout hoping that WaitForInputIdle() will return
863 // much sooner, but not INFINITE just in case the process hangs
864 // completely - like this we will regain control sooner or later
865 switch ( ::WaitForInputIdle(pi
.hProcess
, 10000 /* 10 seconds */) )
868 wxFAIL_MSG( _T("unexpected WaitForInputIdle() return code") );
872 wxLogLastError(_T("WaitForInputIdle() in wxExecute"));
875 wxLogDebug(_T("Timeout too small in WaitForInputIdle"));
881 // ok, process ready to accept DDE requests
882 ok
= wxExecuteDDE(ddeServer
, ddeTopic
, ddeCommand
);
887 wxLogDebug(_T("Failed to send DDE request to the process \"%s\"."),
893 if ( !(flags
& wxEXEC_SYNC
) )
895 // clean up will be done when the process terminates
898 return pi
.dwProcessId
;
901 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
902 wxCHECK_MSG( traits
, -1, _T("no wxAppTraits in wxExecute()?") );
905 if ( !(flags
& wxEXEC_NODISABLE
) )
907 // disable all app windows while waiting for the child process to finish
908 cookie
= traits
->BeforeChildWaitLoop();
911 // wait until the child process terminates
912 while ( data
->state
)
914 #if wxUSE_STREAMS && !defined(__WXWINCE__)
917 #endif // wxUSE_STREAMS
919 // don't eat 100% of the CPU -- ugly but anything else requires
920 // real async IO which we don't have for the moment
923 // we must process messages or we'd never get wxWM_PROC_TERMINATED
924 traits
->AlwaysYield();
927 if ( !(flags
& wxEXEC_NODISABLE
) )
929 // reenable disabled windows back
930 traits
->AfterChildWaitLoop(cookie
);
933 DWORD dwExitCode
= data
->dwExitCode
;
936 // return the exit code
940 long wxExecute(wxChar
**argv
, int flags
, wxProcess
*handler
)
953 return wxExecute(command
, flags
, handler
);