1 /////////////////////////////////////////////////////////////////////////////
2 // Name: msw/utilsexec.cpp
3 // Purpose: wxExecute implementation for MSW
4 // Author: Julian Smart
8 // Copyright: (c) 1998-2002 wxWindows dev team
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
20 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
21 #pragma implementation
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
38 #include "wx/stream.h"
39 #include "wx/process.h"
41 #include "wx/apptrait.h"
43 #include "wx/module.h"
45 #include "wx/msw/private.h"
49 #if !defined(__GNUWIN32__) && !defined(__SALFORDC__) && !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 // ----------------------------------------------------------------------------
108 // ----------------------------------------------------------------------------
110 // structure describing the process we're being waiting for
116 if ( !::CloseHandle(hProcess
) )
118 wxLogLastError(wxT("CloseHandle(hProcess)"));
122 HWND hWnd
; // window to send wxWM_PROC_TERMINATED to
123 HANDLE hProcess
; // handle of the process
124 DWORD dwProcessId
; // pid of the process
126 DWORD dwExitCode
; // the exit code of the process
127 bool state
; // set to FALSE when the process finishes
130 class wxExecuteModule
: public wxModule
133 virtual bool OnInit() { return true; }
134 virtual void OnExit()
136 if ( *gs_classForHiddenWindow
)
138 if ( !::UnregisterClass(wxMSWEXEC_WNDCLASSNAME
, wxGetInstance()) )
140 wxLogLastError(_T("UnregisterClass(wxExecClass)"));
143 gs_classForHiddenWindow
= NULL
;
148 DECLARE_DYNAMIC_CLASS(wxExecuteModule
)
151 #if wxUSE_STREAMS && !defined(__WXWINCE__)
153 // ----------------------------------------------------------------------------
155 // ----------------------------------------------------------------------------
157 class wxPipeInputStream
: public wxInputStream
160 wxPipeInputStream(HANDLE hInput
);
161 virtual ~wxPipeInputStream();
163 // returns TRUE if the pipe is still opened
164 bool IsOpened() const { return m_hInput
!= INVALID_HANDLE_VALUE
; }
166 // returns TRUE if there is any data to be read from the pipe
167 virtual bool CanRead() const;
170 size_t OnSysRead(void *buffer
, size_t len
);
175 DECLARE_NO_COPY_CLASS(wxPipeInputStream
)
178 class wxPipeOutputStream
: public wxOutputStream
181 wxPipeOutputStream(HANDLE hOutput
);
182 virtual ~wxPipeOutputStream();
185 size_t OnSysWrite(const void *buffer
, size_t len
);
190 DECLARE_NO_COPY_CLASS(wxPipeOutputStream
)
193 // define this to let wxexec.cpp know that we know what we're doing
194 #define _WX_USED_BY_WXEXECUTE_
195 #include "../common/execcmn.cpp"
197 // ----------------------------------------------------------------------------
198 // wxPipe represents a Win32 anonymous pipe
199 // ----------------------------------------------------------------------------
204 // the symbolic names for the pipe ends
211 // default ctor doesn't do anything
212 wxPipe() { m_handles
[Read
] = m_handles
[Write
] = INVALID_HANDLE_VALUE
; }
214 // create the pipe, return TRUE if ok, FALSE on error
217 // default secutiry attributes
218 SECURITY_ATTRIBUTES security
;
220 security
.nLength
= sizeof(security
);
221 security
.lpSecurityDescriptor
= NULL
;
222 security
.bInheritHandle
= TRUE
; // to pass it to the child
224 if ( !::CreatePipe(&m_handles
[0], &m_handles
[1], &security
, 0) )
226 wxLogSysError(_("Failed to create an anonymous pipe"));
234 // return TRUE if we were created successfully
235 bool IsOk() const { return m_handles
[Read
] != INVALID_HANDLE_VALUE
; }
237 // return the descriptor for one of the pipe ends
238 HANDLE
operator[](Direction which
) const
240 wxASSERT_MSG( which
>= 0 && (size_t)which
< WXSIZEOF(m_handles
),
241 _T("invalid pipe index") );
243 return m_handles
[which
];
246 // detach a descriptor, meaning that the pipe dtor won't close it, and
248 HANDLE
Detach(Direction which
)
250 wxASSERT_MSG( which
>= 0 && (size_t)which
< WXSIZEOF(m_handles
),
251 _T("invalid pipe index") );
253 HANDLE handle
= m_handles
[which
];
254 m_handles
[which
] = INVALID_HANDLE_VALUE
;
259 // close the pipe descriptors
262 for ( size_t n
= 0; n
< WXSIZEOF(m_handles
); n
++ )
264 if ( m_handles
[n
] != INVALID_HANDLE_VALUE
)
266 ::CloseHandle(m_handles
[n
]);
267 m_handles
[n
] = INVALID_HANDLE_VALUE
;
272 // dtor closes the pipe descriptors
273 ~wxPipe() { Close(); }
279 #endif // wxUSE_STREAMS
281 // ============================================================================
283 // ============================================================================
285 // ----------------------------------------------------------------------------
286 // process termination detecting support
287 // ----------------------------------------------------------------------------
289 // thread function for the thread monitoring the process termination
290 static DWORD __stdcall
wxExecuteThread(void *arg
)
292 wxExecuteData
* const data
= (wxExecuteData
*)arg
;
294 if ( ::WaitForSingleObject(data
->hProcess
, INFINITE
) != WAIT_OBJECT_0
)
296 wxLogDebug(_T("Waiting for the process termination failed!"));
300 if ( !::GetExitCodeProcess(data
->hProcess
, &data
->dwExitCode
) )
302 wxLogLastError(wxT("GetExitCodeProcess"));
305 wxASSERT_MSG( data
->dwExitCode
!= STILL_ACTIVE
,
306 wxT("process should have terminated") );
308 // send a message indicating process termination to the window
309 ::SendMessage(data
->hWnd
, wxWM_PROC_TERMINATED
, 0, (LPARAM
)data
);
314 // window procedure of a hidden window which is created just to receive
315 // the notification message when a process exits
316 LRESULT APIENTRY _EXPORT
wxExecuteWindowCbk(HWND hWnd
, UINT message
,
317 WPARAM wParam
, LPARAM lParam
)
319 if ( message
== wxWM_PROC_TERMINATED
)
321 DestroyWindow(hWnd
); // we don't need it any more
323 wxExecuteData
* const data
= (wxExecuteData
*)lParam
;
326 data
->handler
->OnTerminate((int)data
->dwProcessId
,
327 (int)data
->dwExitCode
);
332 // we're executing synchronously, tell the waiting thread
333 // that the process finished
338 // asynchronous execution - we should do the clean up
346 return ::DefWindowProc(hWnd
, message
, wParam
, lParam
);
350 // ============================================================================
351 // implementation of IO redirection support classes
352 // ============================================================================
354 #if wxUSE_STREAMS && !defined(__WXWINCE__)
356 // ----------------------------------------------------------------------------
357 // wxPipeInputStreams
358 // ----------------------------------------------------------------------------
360 wxPipeInputStream::wxPipeInputStream(HANDLE hInput
)
365 wxPipeInputStream::~wxPipeInputStream()
367 if ( m_hInput
!= INVALID_HANDLE_VALUE
)
368 ::CloseHandle(m_hInput
);
371 bool wxPipeInputStream::CanRead() const
378 // function name is misleading, it works with anon pipes as well
379 DWORD rc
= ::PeekNamedPipe
382 NULL
, 0, // ptr to buffer and its size
383 NULL
, // [out] bytes read
384 &nAvailable
, // [out] bytes available
385 NULL
// [out] bytes left
390 if ( ::GetLastError() != ERROR_BROKEN_PIPE
)
393 wxLogLastError(_T("PeekNamedPipe"));
396 // don't try to continue reading from a pipe if an error occured or if
397 // it had been closed
398 ::CloseHandle(m_hInput
);
400 wxPipeInputStream
*self
= wxConstCast(this, wxPipeInputStream
);
402 self
->m_hInput
= INVALID_HANDLE_VALUE
;
403 self
->m_lasterror
= wxSTREAM_EOF
;
408 return nAvailable
!= 0;
411 size_t wxPipeInputStream::OnSysRead(void *buffer
, size_t len
)
415 m_lasterror
= wxSTREAM_EOF
;
421 if ( !::ReadFile(m_hInput
, buffer
, len
, &bytesRead
, NULL
) )
423 m_lasterror
= ::GetLastError() == ERROR_BROKEN_PIPE
425 : wxSTREAM_READ_ERROR
;
428 // bytesRead is set to 0, as desired, if an error occured
432 // ----------------------------------------------------------------------------
433 // wxPipeOutputStream
434 // ----------------------------------------------------------------------------
436 wxPipeOutputStream::wxPipeOutputStream(HANDLE hOutput
)
441 wxPipeOutputStream::~wxPipeOutputStream()
443 ::CloseHandle(m_hOutput
);
446 size_t wxPipeOutputStream::OnSysWrite(const void *buffer
, size_t len
)
450 m_lasterror
= wxSTREAM_NO_ERROR
;
451 if ( !::WriteFile(m_hOutput
, buffer
, len
, &bytesWritten
, NULL
) )
453 m_lasterror
= ::GetLastError() == ERROR_BROKEN_PIPE
455 : wxSTREAM_WRITE_ERROR
;
461 #endif // wxUSE_STREAMS
463 // ============================================================================
464 // wxExecute functions family
465 // ============================================================================
469 // connect to the given server via DDE and ask it to execute the command
470 static bool wxExecuteDDE(const wxString
& ddeServer
,
471 const wxString
& ddeTopic
,
472 const wxString
& ddeCommand
)
474 bool ok
wxDUMMY_INITIALIZE(false);
477 wxConnectionBase
*conn
= client
.MakeConnection(wxEmptyString
,
484 else // connected to DDE server
486 // the added complication here is that although most programs use
487 // XTYP_EXECUTE for their DDE API, some important ones -- like Word
488 // and other MS stuff - use XTYP_REQUEST!
490 // moreover, anotheri mportant program (IE) understands both but
491 // returns an error from Execute() so we must try Request() first
492 // to avoid doing it twice
494 // we're prepared for this one to fail, so don't show errors
497 ok
= conn
->Request(ddeCommand
) != NULL
;
502 // now try execute -- but show the errors
503 ok
= conn
->Execute(ddeCommand
);
512 long wxExecute(const wxString
& cmd
, int flags
, wxProcess
*handler
)
514 wxCHECK_MSG( !!cmd
, 0, wxT("empty command in wxExecute") );
517 // for many reasons, the code below breaks down if it's called from another
518 // thread -- this could be fixed, but as Unix versions don't support this
519 // neither I don't want to waste time on this now
520 wxASSERT_MSG( wxThread::IsMain(),
521 _T("wxExecute() can be called only from the main thread") );
522 #endif // wxUSE_THREADS
527 // DDE hack: this is really not pretty, but we need to allow this for
528 // transparent handling of DDE servers in wxMimeTypesManager. Usually it
529 // returns the command which should be run to view/open/... a file of the
530 // given type. Sometimes, however, this command just launches the server
531 // and an additional DDE request must be made to really open the file. To
532 // keep all this well hidden from the application, we allow a special form
533 // of command: WX_DDE#<command>#DDE_SERVER#DDE_TOPIC#DDE_COMMAND in which
534 // case we execute just <command> and process the rest below
535 wxString ddeServer
, ddeTopic
, ddeCommand
;
536 static const size_t lenDdePrefix
= 7; // strlen("WX_DDE:")
537 if ( cmd
.Left(lenDdePrefix
) == _T("WX_DDE#") )
539 // speed up the concatenations below
540 ddeServer
.reserve(256);
541 ddeTopic
.reserve(256);
542 ddeCommand
.reserve(256);
544 const wxChar
*p
= cmd
.c_str() + 7;
545 while ( *p
&& *p
!= _T('#') )
557 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
560 while ( *p
&& *p
!= _T('#') )
572 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
575 while ( *p
&& *p
!= _T('#') )
587 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
595 // if we want to just launch the program and not wait for its
596 // termination, try to execute DDE command right now, it can succeed if
597 // the process is already running - but as it fails if it's not
598 // running, suppress any errors it might generate
599 if ( !(flags
& wxEXEC_SYNC
) )
602 if ( wxExecuteDDE(ddeServer
, ddeTopic
, ddeCommand
) )
604 // a dummy PID - this is a hack, of course, but it's well worth
605 // it as we don't open a new server each time we're called
606 // which would be quite bad
618 // the IO redirection is only supported with wxUSE_STREAMS
619 BOOL redirect
= FALSE
;
621 #if wxUSE_STREAMS && !defined(__WXWINCE__)
622 wxPipe pipeIn
, pipeOut
, pipeErr
;
624 // we'll save here the copy of pipeIn[Write]
625 HANDLE hpipeStdinWrite
= INVALID_HANDLE_VALUE
;
627 // open the pipes to which child process IO will be redirected if needed
628 if ( handler
&& handler
->IsRedirected() )
630 // create pipes for redirecting stdin, stdout and stderr
631 if ( !pipeIn
.Create() || !pipeOut
.Create() || !pipeErr
.Create() )
633 wxLogSysError(_("Failed to redirect the child process IO"));
635 // indicate failure: we need to return different error code
636 // depending on the sync flag
637 return flags
& wxEXEC_SYNC
? -1 : 0;
642 #endif // wxUSE_STREAMS
644 // create the process
649 #if wxUSE_STREAMS && !defined(__WXWINCE__)
652 si
.dwFlags
= STARTF_USESTDHANDLES
;
654 si
.hStdInput
= pipeIn
[wxPipe::Read
];
655 si
.hStdOutput
= pipeOut
[wxPipe::Write
];
656 si
.hStdError
= pipeErr
[wxPipe::Write
];
658 // when the std IO is redirected, we don't show the (console) process
659 // window by default, but this can be overridden by the caller by
660 // specifying wxEXEC_NOHIDE flag
661 if ( !(flags
& wxEXEC_NOHIDE
) )
663 si
.dwFlags
|= STARTF_USESHOWWINDOW
;
664 si
.wShowWindow
= SW_HIDE
;
667 // we must duplicate the handle to the write side of stdin pipe to make
668 // it non inheritable: indeed, we must close the writing end of pipeIn
669 // before launching the child process as otherwise this handle will be
670 // inherited by the child which will never close it and so the pipe
671 // will never be closed and the child will be left stuck in ReadFile()
672 HANDLE pipeInWrite
= pipeIn
.Detach(wxPipe::Write
);
673 if ( !::DuplicateHandle
675 ::GetCurrentProcess(),
677 ::GetCurrentProcess(),
679 0, // desired access: unused here
680 FALSE
, // not inherited
681 DUPLICATE_SAME_ACCESS
// same access as for src handle
684 wxLogLastError(_T("DuplicateHandle"));
687 ::CloseHandle(pipeInWrite
);
689 #endif // wxUSE_STREAMS
691 PROCESS_INFORMATION pi
;
692 DWORD dwFlags
= CREATE_SUSPENDED
;
694 dwFlags
|= CREATE_DEFAULT_ERROR_MODE
;
697 bool ok
= ::CreateProcess
699 NULL
, // application name (use only cmd line)
701 command
.c_str(), // full command line
702 NULL
, // security attributes: defaults for both
703 NULL
, // the process and its main thread
704 redirect
, // inherit handles if we use pipes
705 dwFlags
, // process creation flags
706 NULL
, // environment (use the same)
707 NULL
, // current directory (use the same)
708 &si
, // startup info (unused here)
712 #if wxUSE_STREAMS && !defined(__WXWINCE__)
713 // we can close the pipe ends used by child anyhow
716 ::CloseHandle(pipeIn
.Detach(wxPipe::Read
));
717 ::CloseHandle(pipeOut
.Detach(wxPipe::Write
));
718 ::CloseHandle(pipeErr
.Detach(wxPipe::Write
));
720 #endif // wxUSE_STREAMS
724 #if wxUSE_STREAMS && !defined(__WXWINCE__)
725 // close the other handles too
728 ::CloseHandle(pipeOut
.Detach(wxPipe::Read
));
729 ::CloseHandle(pipeErr
.Detach(wxPipe::Read
));
731 #endif // wxUSE_STREAMS
733 wxLogSysError(_("Execution of command '%s' failed"), command
.c_str());
735 return flags
& wxEXEC_SYNC
? -1 : 0;
738 #if wxUSE_STREAMS && !defined(__WXWINCE__)
739 // the input buffer bufOut is connected to stdout, this is why it is
740 // called bufOut and not bufIn
741 wxStreamTempInputBuffer bufOut
,
746 // We can now initialize the wxStreams
748 outStream
= new wxPipeInputStream(pipeOut
.Detach(wxPipe::Read
));
750 errStream
= new wxPipeInputStream(pipeErr
.Detach(wxPipe::Read
));
752 inStream
= new wxPipeOutputStream(hpipeStdinWrite
);
754 handler
->SetPipeStreams(outStream
, inStream
, errStream
);
756 bufOut
.Init(outStream
);
757 bufErr
.Init(errStream
);
759 #endif // wxUSE_STREAMS
761 // create a hidden window to receive notification about process
763 HWND hwnd
= wxCreateHiddenWindow
765 &gs_classForHiddenWindow
,
766 wxMSWEXEC_WNDCLASSNAME
,
767 (WNDPROC
)wxExecuteWindowCbk
770 wxASSERT_MSG( hwnd
, wxT("can't create a hidden window for wxExecute") );
773 wxExecuteData
*data
= new wxExecuteData
;
774 data
->hProcess
= pi
.hProcess
;
775 data
->dwProcessId
= pi
.dwProcessId
;
777 data
->state
= (flags
& wxEXEC_SYNC
) != 0;
778 if ( flags
& wxEXEC_SYNC
)
780 // handler may be !NULL for capturing program output, but we don't use
781 // it wxExecuteData struct in this case
782 data
->handler
= NULL
;
786 // may be NULL or not
787 data
->handler
= handler
;
791 HANDLE hThread
= ::CreateThread(NULL
,
798 // resume process we created now - whether the thread creation succeeded or
800 if ( ::ResumeThread(pi
.hThread
) == (DWORD
)-1 )
802 // ignore it - what can we do?
803 wxLogLastError(wxT("ResumeThread in wxExecute"));
806 // close unneeded handle
807 if ( !::CloseHandle(pi
.hThread
) )
808 wxLogLastError(wxT("CloseHandle(hThread)"));
812 wxLogLastError(wxT("CreateThread in wxExecute"));
817 // the process still started up successfully...
818 return pi
.dwProcessId
;
821 ::CloseHandle(hThread
);
823 #if wxUSE_IPC && !defined(__WXWINCE__)
824 // second part of DDE hack: now establish the DDE conversation with the
825 // just launched process
826 if ( !ddeServer
.empty() )
830 // give the process the time to init itself
832 // we use a very big timeout hoping that WaitForInputIdle() will return
833 // much sooner, but not INFINITE just in case the process hangs
834 // completely - like this we will regain control sooner or later
835 switch ( ::WaitForInputIdle(pi
.hProcess
, 10000 /* 10 seconds */) )
838 wxFAIL_MSG( _T("unexpected WaitForInputIdle() return code") );
842 wxLogLastError(_T("WaitForInputIdle() in wxExecute"));
845 wxLogDebug(_T("Timeout too small in WaitForInputIdle"));
851 // ok, process ready to accept DDE requests
852 ok
= wxExecuteDDE(ddeServer
, ddeTopic
, ddeCommand
);
857 wxLogDebug(_T("Failed to send DDE request to the process \"%s\"."),
863 if ( !(flags
& wxEXEC_SYNC
) )
865 // clean up will be done when the process terminates
868 return pi
.dwProcessId
;
871 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
872 wxCHECK_MSG( traits
, -1, _T("no wxAppTraits in wxExecute()?") );
874 // disable all app windows while waiting for the child process to finish
875 void *cookie
= traits
->BeforeChildWaitLoop();
877 // wait until the child process terminates
878 while ( data
->state
)
880 #if wxUSE_STREAMS && !defined(__WXWINCE__)
883 #endif // wxUSE_STREAMS
885 // don't eat 100% of the CPU -- ugly but anything else requires
886 // real async IO which we don't have for the moment
889 // we must process messages or we'd never get wxWM_PROC_TERMINATED
890 traits
->AlwaysYield();
893 traits
->AfterChildWaitLoop(cookie
);
895 DWORD dwExitCode
= data
->dwExitCode
;
898 // return the exit code
902 long wxExecute(wxChar
**argv
, int flags
, wxProcess
*handler
)
915 return wxExecute(command
, flags
, handler
);