1 /////////////////////////////////////////////////////////////////////////////
2 // Name: msw/utilsexec.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 #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() { Close(); }
186 size_t OnSysWrite(const void *buffer
, size_t len
);
191 DECLARE_NO_COPY_CLASS(wxPipeOutputStream
)
194 // define this to let wxexec.cpp know that we know what we're doing
195 #define _WX_USED_BY_WXEXECUTE_
196 #include "../common/execcmn.cpp"
198 // ----------------------------------------------------------------------------
199 // wxPipe represents a Win32 anonymous pipe
200 // ----------------------------------------------------------------------------
205 // the symbolic names for the pipe ends
212 // default ctor doesn't do anything
213 wxPipe() { m_handles
[Read
] = m_handles
[Write
] = INVALID_HANDLE_VALUE
; }
215 // create the pipe, return true if ok, false on error
218 // default secutiry attributes
219 SECURITY_ATTRIBUTES security
;
221 security
.nLength
= sizeof(security
);
222 security
.lpSecurityDescriptor
= NULL
;
223 security
.bInheritHandle
= TRUE
; // to pass it to the child
225 if ( !::CreatePipe(&m_handles
[0], &m_handles
[1], &security
, 0) )
227 wxLogSysError(_("Failed to create an anonymous pipe"));
235 // return true if we were created successfully
236 bool IsOk() const { return m_handles
[Read
] != INVALID_HANDLE_VALUE
; }
238 // return the descriptor for one of the pipe ends
239 HANDLE
operator[](Direction which
) const { return m_handles
[which
]; }
241 // detach a descriptor, meaning that the pipe dtor won't close it, and
243 HANDLE
Detach(Direction which
)
245 HANDLE handle
= m_handles
[which
];
246 m_handles
[which
] = INVALID_HANDLE_VALUE
;
251 // close the pipe descriptors
254 for ( size_t n
= 0; n
< WXSIZEOF(m_handles
); n
++ )
256 if ( m_handles
[n
] != INVALID_HANDLE_VALUE
)
258 ::CloseHandle(m_handles
[n
]);
259 m_handles
[n
] = INVALID_HANDLE_VALUE
;
264 // dtor closes the pipe descriptors
265 ~wxPipe() { Close(); }
271 #endif // wxUSE_STREAMS
273 // ============================================================================
275 // ============================================================================
277 // ----------------------------------------------------------------------------
278 // process termination detecting support
279 // ----------------------------------------------------------------------------
281 // thread function for the thread monitoring the process termination
282 static DWORD __stdcall
wxExecuteThread(void *arg
)
284 wxExecuteData
* const data
= (wxExecuteData
*)arg
;
286 if ( ::WaitForSingleObject(data
->hProcess
, INFINITE
) != WAIT_OBJECT_0
)
288 wxLogDebug(_T("Waiting for the process termination failed!"));
292 if ( !::GetExitCodeProcess(data
->hProcess
, &data
->dwExitCode
) )
294 wxLogLastError(wxT("GetExitCodeProcess"));
297 wxASSERT_MSG( data
->dwExitCode
!= STILL_ACTIVE
,
298 wxT("process should have terminated") );
300 // send a message indicating process termination to the window
301 ::SendMessage(data
->hWnd
, wxWM_PROC_TERMINATED
, 0, (LPARAM
)data
);
306 // window procedure of a hidden window which is created just to receive
307 // the notification message when a process exits
308 LRESULT APIENTRY _EXPORT
wxExecuteWindowCbk(HWND hWnd
, UINT message
,
309 WPARAM wParam
, LPARAM lParam
)
311 if ( message
== wxWM_PROC_TERMINATED
)
313 DestroyWindow(hWnd
); // we don't need it any more
315 wxExecuteData
* const data
= (wxExecuteData
*)lParam
;
318 data
->handler
->OnTerminate((int)data
->dwProcessId
,
319 (int)data
->dwExitCode
);
324 // we're executing synchronously, tell the waiting thread
325 // that the process finished
330 // asynchronous execution - we should do the clean up
338 return ::DefWindowProc(hWnd
, message
, wParam
, lParam
);
342 // ============================================================================
343 // implementation of IO redirection support classes
344 // ============================================================================
346 #if wxUSE_STREAMS && !defined(__WXWINCE__)
348 // ----------------------------------------------------------------------------
349 // wxPipeInputStreams
350 // ----------------------------------------------------------------------------
352 wxPipeInputStream::wxPipeInputStream(HANDLE hInput
)
357 wxPipeInputStream::~wxPipeInputStream()
359 if ( m_hInput
!= INVALID_HANDLE_VALUE
)
360 ::CloseHandle(m_hInput
);
363 bool wxPipeInputStream::CanRead() const
370 // function name is misleading, it works with anon pipes as well
371 DWORD rc
= ::PeekNamedPipe
374 NULL
, 0, // ptr to buffer and its size
375 NULL
, // [out] bytes read
376 &nAvailable
, // [out] bytes available
377 NULL
// [out] bytes left
382 if ( ::GetLastError() != ERROR_BROKEN_PIPE
)
385 wxLogLastError(_T("PeekNamedPipe"));
388 // don't try to continue reading from a pipe if an error occured or if
389 // it had been closed
390 ::CloseHandle(m_hInput
);
392 wxPipeInputStream
*self
= wxConstCast(this, wxPipeInputStream
);
394 self
->m_hInput
= INVALID_HANDLE_VALUE
;
395 self
->m_lasterror
= wxSTREAM_EOF
;
400 return nAvailable
!= 0;
403 size_t wxPipeInputStream::OnSysRead(void *buffer
, size_t len
)
407 m_lasterror
= wxSTREAM_EOF
;
413 if ( !::ReadFile(m_hInput
, buffer
, len
, &bytesRead
, NULL
) )
415 m_lasterror
= ::GetLastError() == ERROR_BROKEN_PIPE
417 : wxSTREAM_READ_ERROR
;
420 // bytesRead is set to 0, as desired, if an error occured
424 // ----------------------------------------------------------------------------
425 // wxPipeOutputStream
426 // ----------------------------------------------------------------------------
428 wxPipeOutputStream::wxPipeOutputStream(HANDLE hOutput
)
432 // unblock the pipe to prevent deadlocks when we're writing to the pipe
433 // from which the child process can't read because it is writing in its own
435 DWORD mode
= PIPE_READMODE_BYTE
| PIPE_NOWAIT
;
436 if ( !::SetNamedPipeHandleState
440 NULL
, // collection count (we don't set it)
441 NULL
// timeout (we don't set it neither)
444 wxLogLastError(_T("SetNamedPipeHandleState(PIPE_NOWAIT)"));
448 bool wxPipeOutputStream::Close()
450 return ::CloseHandle(m_hOutput
) != 0;
454 size_t wxPipeOutputStream::OnSysWrite(const void *buffer
, size_t len
)
456 m_lasterror
= wxSTREAM_NO_ERROR
;
458 DWORD totalWritten
= 0;
462 if ( !::WriteFile(m_hOutput
, buffer
, len
, &chunkWritten
, NULL
) )
464 m_lasterror
= ::GetLastError() == ERROR_BROKEN_PIPE
466 : wxSTREAM_WRITE_ERROR
;
473 buffer
= (char *)buffer
+ chunkWritten
;
474 totalWritten
+= chunkWritten
;
481 #endif // wxUSE_STREAMS
483 // ============================================================================
484 // wxExecute functions family
485 // ============================================================================
489 // connect to the given server via DDE and ask it to execute the command
490 static bool wxExecuteDDE(const wxString
& ddeServer
,
491 const wxString
& ddeTopic
,
492 const wxString
& ddeCommand
)
494 bool ok
wxDUMMY_INITIALIZE(false);
497 wxConnectionBase
*conn
= client
.MakeConnection(wxEmptyString
,
504 else // connected to DDE server
506 // the added complication here is that although most programs use
507 // XTYP_EXECUTE for their DDE API, some important ones -- like Word
508 // and other MS stuff - use XTYP_REQUEST!
510 // moreover, anotheri mportant program (IE) understands both but
511 // returns an error from Execute() so we must try Request() first
512 // to avoid doing it twice
514 // we're prepared for this one to fail, so don't show errors
517 ok
= conn
->Request(ddeCommand
) != NULL
;
522 // now try execute -- but show the errors
523 ok
= conn
->Execute(ddeCommand
);
532 long wxExecute(const wxString
& cmd
, int flags
, wxProcess
*handler
)
534 wxCHECK_MSG( !cmd
.empty(), 0, wxT("empty command in wxExecute") );
537 // for many reasons, the code below breaks down if it's called from another
538 // thread -- this could be fixed, but as Unix versions don't support this
539 // neither I don't want to waste time on this now
540 wxASSERT_MSG( wxThread::IsMain(),
541 _T("wxExecute() can be called only from the main thread") );
542 #endif // wxUSE_THREADS
547 // DDE hack: this is really not pretty, but we need to allow this for
548 // transparent handling of DDE servers in wxMimeTypesManager. Usually it
549 // returns the command which should be run to view/open/... a file of the
550 // given type. Sometimes, however, this command just launches the server
551 // and an additional DDE request must be made to really open the file. To
552 // keep all this well hidden from the application, we allow a special form
553 // of command: WX_DDE#<command>#DDE_SERVER#DDE_TOPIC#DDE_COMMAND in which
554 // case we execute just <command> and process the rest below
555 wxString ddeServer
, ddeTopic
, ddeCommand
;
556 static const size_t lenDdePrefix
= 7; // strlen("WX_DDE:")
557 if ( cmd
.Left(lenDdePrefix
) == _T("WX_DDE#") )
559 // speed up the concatenations below
560 ddeServer
.reserve(256);
561 ddeTopic
.reserve(256);
562 ddeCommand
.reserve(256);
564 const wxChar
*p
= cmd
.c_str() + 7;
565 while ( *p
&& *p
!= _T('#') )
577 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
580 while ( *p
&& *p
!= _T('#') )
592 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
595 while ( *p
&& *p
!= _T('#') )
607 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
615 // if we want to just launch the program and not wait for its
616 // termination, try to execute DDE command right now, it can succeed if
617 // the process is already running - but as it fails if it's not
618 // running, suppress any errors it might generate
619 if ( !(flags
& wxEXEC_SYNC
) )
622 if ( wxExecuteDDE(ddeServer
, ddeTopic
, ddeCommand
) )
624 // a dummy PID - this is a hack, of course, but it's well worth
625 // it as we don't open a new server each time we're called
626 // which would be quite bad
638 // the IO redirection is only supported with wxUSE_STREAMS
639 BOOL redirect
= FALSE
;
641 #if wxUSE_STREAMS && !defined(__WXWINCE__)
642 wxPipe pipeIn
, pipeOut
, pipeErr
;
644 // we'll save here the copy of pipeIn[Write]
645 HANDLE hpipeStdinWrite
= INVALID_HANDLE_VALUE
;
647 // open the pipes to which child process IO will be redirected if needed
648 if ( handler
&& handler
->IsRedirected() )
650 // create pipes for redirecting stdin, stdout and stderr
651 if ( !pipeIn
.Create() || !pipeOut
.Create() || !pipeErr
.Create() )
653 wxLogSysError(_("Failed to redirect the child process IO"));
655 // indicate failure: we need to return different error code
656 // depending on the sync flag
657 return flags
& wxEXEC_SYNC
? -1 : 0;
662 #endif // wxUSE_STREAMS
664 // create the process
669 #if wxUSE_STREAMS && !defined(__WXWINCE__)
672 si
.dwFlags
= STARTF_USESTDHANDLES
;
674 si
.hStdInput
= pipeIn
[wxPipe::Read
];
675 si
.hStdOutput
= pipeOut
[wxPipe::Write
];
676 si
.hStdError
= pipeErr
[wxPipe::Write
];
678 // when the std IO is redirected, we don't show the (console) process
679 // window by default, but this can be overridden by the caller by
680 // specifying wxEXEC_NOHIDE flag
681 if ( !(flags
& wxEXEC_NOHIDE
) )
683 si
.dwFlags
|= STARTF_USESHOWWINDOW
;
684 si
.wShowWindow
= SW_HIDE
;
687 // we must duplicate the handle to the write side of stdin pipe to make
688 // it non inheritable: indeed, we must close the writing end of pipeIn
689 // before launching the child process as otherwise this handle will be
690 // inherited by the child which will never close it and so the pipe
691 // will never be closed and the child will be left stuck in ReadFile()
692 HANDLE pipeInWrite
= pipeIn
.Detach(wxPipe::Write
);
693 if ( !::DuplicateHandle
695 ::GetCurrentProcess(),
697 ::GetCurrentProcess(),
699 0, // desired access: unused here
700 FALSE
, // not inherited
701 DUPLICATE_SAME_ACCESS
// same access as for src handle
704 wxLogLastError(_T("DuplicateHandle"));
707 ::CloseHandle(pipeInWrite
);
709 #endif // wxUSE_STREAMS
711 PROCESS_INFORMATION pi
;
712 DWORD dwFlags
= CREATE_SUSPENDED
;
714 dwFlags
|= CREATE_DEFAULT_ERROR_MODE
;
717 bool ok
= ::CreateProcess
719 NULL
, // application name (use only cmd line)
721 command
.c_str(), // full command line
722 NULL
, // security attributes: defaults for both
723 NULL
, // the process and its main thread
724 redirect
, // inherit handles if we use pipes
725 dwFlags
, // process creation flags
726 NULL
, // environment (use the same)
727 NULL
, // current directory (use the same)
728 &si
, // startup info (unused here)
732 #if wxUSE_STREAMS && !defined(__WXWINCE__)
733 // we can close the pipe ends used by child anyhow
736 ::CloseHandle(pipeIn
.Detach(wxPipe::Read
));
737 ::CloseHandle(pipeOut
.Detach(wxPipe::Write
));
738 ::CloseHandle(pipeErr
.Detach(wxPipe::Write
));
740 #endif // wxUSE_STREAMS
744 #if wxUSE_STREAMS && !defined(__WXWINCE__)
745 // close the other handles too
748 ::CloseHandle(pipeOut
.Detach(wxPipe::Read
));
749 ::CloseHandle(pipeErr
.Detach(wxPipe::Read
));
751 #endif // wxUSE_STREAMS
753 wxLogSysError(_("Execution of command '%s' failed"), command
.c_str());
755 return flags
& wxEXEC_SYNC
? -1 : 0;
758 #if wxUSE_STREAMS && !defined(__WXWINCE__)
759 // the input buffer bufOut is connected to stdout, this is why it is
760 // called bufOut and not bufIn
761 wxStreamTempInputBuffer bufOut
,
766 // We can now initialize the wxStreams
768 outStream
= new wxPipeInputStream(pipeOut
.Detach(wxPipe::Read
));
770 errStream
= new wxPipeInputStream(pipeErr
.Detach(wxPipe::Read
));
772 inStream
= new wxPipeOutputStream(hpipeStdinWrite
);
774 handler
->SetPipeStreams(outStream
, inStream
, errStream
);
776 bufOut
.Init(outStream
);
777 bufErr
.Init(errStream
);
779 #endif // wxUSE_STREAMS
781 // create a hidden window to receive notification about process
783 HWND hwnd
= wxCreateHiddenWindow
785 &gs_classForHiddenWindow
,
786 wxMSWEXEC_WNDCLASSNAME
,
787 (WNDPROC
)wxExecuteWindowCbk
790 wxASSERT_MSG( hwnd
, wxT("can't create a hidden window for wxExecute") );
793 wxExecuteData
*data
= new wxExecuteData
;
794 data
->hProcess
= pi
.hProcess
;
795 data
->dwProcessId
= pi
.dwProcessId
;
797 data
->state
= (flags
& wxEXEC_SYNC
) != 0;
798 if ( flags
& wxEXEC_SYNC
)
800 // handler may be !NULL for capturing program output, but we don't use
801 // it wxExecuteData struct in this case
802 data
->handler
= NULL
;
806 // may be NULL or not
807 data
->handler
= handler
;
811 HANDLE hThread
= ::CreateThread(NULL
,
818 // resume process we created now - whether the thread creation succeeded or
820 if ( ::ResumeThread(pi
.hThread
) == (DWORD
)-1 )
822 // ignore it - what can we do?
823 wxLogLastError(wxT("ResumeThread in wxExecute"));
826 // close unneeded handle
827 if ( !::CloseHandle(pi
.hThread
) )
828 wxLogLastError(wxT("CloseHandle(hThread)"));
832 wxLogLastError(wxT("CreateThread in wxExecute"));
837 // the process still started up successfully...
838 return pi
.dwProcessId
;
841 ::CloseHandle(hThread
);
843 #if wxUSE_IPC && !defined(__WXWINCE__)
844 // second part of DDE hack: now establish the DDE conversation with the
845 // just launched process
846 if ( !ddeServer
.empty() )
850 // give the process the time to init itself
852 // we use a very big timeout hoping that WaitForInputIdle() will return
853 // much sooner, but not INFINITE just in case the process hangs
854 // completely - like this we will regain control sooner or later
855 switch ( ::WaitForInputIdle(pi
.hProcess
, 10000 /* 10 seconds */) )
858 wxFAIL_MSG( _T("unexpected WaitForInputIdle() return code") );
862 wxLogLastError(_T("WaitForInputIdle() in wxExecute"));
865 wxLogDebug(_T("Timeout too small in WaitForInputIdle"));
871 // ok, process ready to accept DDE requests
872 ok
= wxExecuteDDE(ddeServer
, ddeTopic
, ddeCommand
);
877 wxLogDebug(_T("Failed to send DDE request to the process \"%s\"."),
883 if ( !(flags
& wxEXEC_SYNC
) )
885 // clean up will be done when the process terminates
888 return pi
.dwProcessId
;
891 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
892 wxCHECK_MSG( traits
, -1, _T("no wxAppTraits in wxExecute()?") );
895 if ( !(flags
& wxEXEC_NODISABLE
) )
897 // disable all app windows while waiting for the child process to finish
898 cookie
= traits
->BeforeChildWaitLoop();
901 // wait until the child process terminates
902 while ( data
->state
)
904 #if wxUSE_STREAMS && !defined(__WXWINCE__)
907 #endif // wxUSE_STREAMS
909 // don't eat 100% of the CPU -- ugly but anything else requires
910 // real async IO which we don't have for the moment
913 // we must process messages or we'd never get wxWM_PROC_TERMINATED
914 traits
->AlwaysYield();
917 if ( !(flags
& wxEXEC_NODISABLE
) )
919 // reenable disabled windows back
920 traits
->AfterChildWaitLoop(cookie
);
923 DWORD dwExitCode
= data
->dwExitCode
;
926 // return the exit code
930 long wxExecute(wxChar
**argv
, int flags
, wxProcess
*handler
)
943 return wxExecute(command
, flags
, handler
);