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"
43 #include "wx/msw/private.h"
47 #if !defined(__GNUWIN32__) && !defined(__SALFORDC__) && !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 // implemented in utils.cpp
84 extern "C" WXDLLIMPEXP_BASE HWND
85 wxCreateHiddenWindow(LPCTSTR
*pclassname
, LPCTSTR classname
, WNDPROC wndproc
);
87 // ----------------------------------------------------------------------------
89 // ----------------------------------------------------------------------------
91 // this message is sent when the process we're waiting for terminates
92 #define wxWM_PROC_TERMINATED (WM_USER + 10000)
94 // ----------------------------------------------------------------------------
95 // this module globals
96 // ----------------------------------------------------------------------------
98 // we need to create a hidden window to receive the process termination
99 // notifications and for this we need a (Win) class name for it which we will
100 // register the first time it's needed
101 static const wxChar
*wxMSWEXEC_WNDCLASSNAME
= wxT("_wxExecute_Internal_Class");
102 static const wxChar
*gs_classForHiddenWindow
= NULL
;
104 // ----------------------------------------------------------------------------
106 // ----------------------------------------------------------------------------
108 // structure describing the process we're being waiting for
114 if ( !::CloseHandle(hProcess
) )
116 wxLogLastError(wxT("CloseHandle(hProcess)"));
120 HWND hWnd
; // window to send wxWM_PROC_TERMINATED to
121 HANDLE hProcess
; // handle of the process
122 DWORD dwProcessId
; // pid of the process
124 DWORD dwExitCode
; // the exit code of the process
125 bool state
; // set to false when the process finishes
128 class wxExecuteModule
: public wxModule
131 virtual bool OnInit() { return true; }
132 virtual void OnExit()
134 if ( *gs_classForHiddenWindow
)
136 if ( !::UnregisterClass(wxMSWEXEC_WNDCLASSNAME
, wxGetInstance()) )
138 wxLogLastError(_T("UnregisterClass(wxExecClass)"));
141 gs_classForHiddenWindow
= NULL
;
146 DECLARE_DYNAMIC_CLASS(wxExecuteModule
)
149 #if wxUSE_STREAMS && !defined(__WXWINCE__)
151 // ----------------------------------------------------------------------------
153 // ----------------------------------------------------------------------------
155 class wxPipeInputStream
: public wxInputStream
158 wxPipeInputStream(HANDLE hInput
);
159 virtual ~wxPipeInputStream();
161 // returns true if the pipe is still opened
162 bool IsOpened() const { return m_hInput
!= INVALID_HANDLE_VALUE
; }
164 // returns true if there is any data to be read from the pipe
165 virtual bool CanRead() const;
168 size_t OnSysRead(void *buffer
, size_t len
);
173 DECLARE_NO_COPY_CLASS(wxPipeInputStream
)
176 class wxPipeOutputStream
: public wxOutputStream
179 wxPipeOutputStream(HANDLE hOutput
);
180 virtual ~wxPipeOutputStream() { Close(); }
184 size_t OnSysWrite(const void *buffer
, size_t len
);
189 DECLARE_NO_COPY_CLASS(wxPipeOutputStream
)
192 // define this to let wxexec.cpp know that we know what we're doing
193 #define _WX_USED_BY_WXEXECUTE_
194 #include "../common/execcmn.cpp"
196 // ----------------------------------------------------------------------------
197 // wxPipe represents a Win32 anonymous pipe
198 // ----------------------------------------------------------------------------
203 // the symbolic names for the pipe ends
210 // default ctor doesn't do anything
211 wxPipe() { m_handles
[Read
] = m_handles
[Write
] = INVALID_HANDLE_VALUE
; }
213 // create the pipe, return true if ok, false on error
216 // default secutiry attributes
217 SECURITY_ATTRIBUTES security
;
219 security
.nLength
= sizeof(security
);
220 security
.lpSecurityDescriptor
= NULL
;
221 security
.bInheritHandle
= TRUE
; // to pass it to the child
223 if ( !::CreatePipe(&m_handles
[0], &m_handles
[1], &security
, 0) )
225 wxLogSysError(_("Failed to create an anonymous pipe"));
233 // return true if we were created successfully
234 bool IsOk() const { return m_handles
[Read
] != INVALID_HANDLE_VALUE
; }
236 // return the descriptor for one of the pipe ends
237 HANDLE
operator[](Direction which
) const { return m_handles
[which
]; }
239 // detach a descriptor, meaning that the pipe dtor won't close it, and
241 HANDLE
Detach(Direction which
)
243 HANDLE handle
= m_handles
[which
];
244 m_handles
[which
] = INVALID_HANDLE_VALUE
;
249 // close the pipe descriptors
252 for ( size_t n
= 0; n
< WXSIZEOF(m_handles
); n
++ )
254 if ( m_handles
[n
] != INVALID_HANDLE_VALUE
)
256 ::CloseHandle(m_handles
[n
]);
257 m_handles
[n
] = INVALID_HANDLE_VALUE
;
262 // dtor closes the pipe descriptors
263 ~wxPipe() { Close(); }
269 #endif // wxUSE_STREAMS
271 // ============================================================================
273 // ============================================================================
275 // ----------------------------------------------------------------------------
276 // process termination detecting support
277 // ----------------------------------------------------------------------------
279 // thread function for the thread monitoring the process termination
280 static DWORD __stdcall
wxExecuteThread(void *arg
)
282 wxExecuteData
* const data
= (wxExecuteData
*)arg
;
284 if ( ::WaitForSingleObject(data
->hProcess
, INFINITE
) != WAIT_OBJECT_0
)
286 wxLogDebug(_T("Waiting for the process termination failed!"));
290 if ( !::GetExitCodeProcess(data
->hProcess
, &data
->dwExitCode
) )
292 wxLogLastError(wxT("GetExitCodeProcess"));
295 wxASSERT_MSG( data
->dwExitCode
!= STILL_ACTIVE
,
296 wxT("process should have terminated") );
298 // send a message indicating process termination to the window
299 ::SendMessage(data
->hWnd
, wxWM_PROC_TERMINATED
, 0, (LPARAM
)data
);
304 // window procedure of a hidden window which is created just to receive
305 // the notification message when a process exits
306 LRESULT APIENTRY _EXPORT
wxExecuteWindowCbk(HWND hWnd
, UINT message
,
307 WPARAM wParam
, LPARAM lParam
)
309 if ( message
== wxWM_PROC_TERMINATED
)
311 DestroyWindow(hWnd
); // we don't need it any more
313 wxExecuteData
* const data
= (wxExecuteData
*)lParam
;
316 data
->handler
->OnTerminate((int)data
->dwProcessId
,
317 (int)data
->dwExitCode
);
322 // we're executing synchronously, tell the waiting thread
323 // that the process finished
328 // asynchronous execution - we should do the clean up
336 return ::DefWindowProc(hWnd
, message
, wParam
, lParam
);
340 // ============================================================================
341 // implementation of IO redirection support classes
342 // ============================================================================
344 #if wxUSE_STREAMS && !defined(__WXWINCE__)
346 // ----------------------------------------------------------------------------
347 // wxPipeInputStreams
348 // ----------------------------------------------------------------------------
350 wxPipeInputStream::wxPipeInputStream(HANDLE hInput
)
355 wxPipeInputStream::~wxPipeInputStream()
357 if ( m_hInput
!= INVALID_HANDLE_VALUE
)
358 ::CloseHandle(m_hInput
);
361 bool wxPipeInputStream::CanRead() const
368 // function name is misleading, it works with anon pipes as well
369 DWORD rc
= ::PeekNamedPipe
372 NULL
, 0, // ptr to buffer and its size
373 NULL
, // [out] bytes read
374 &nAvailable
, // [out] bytes available
375 NULL
// [out] bytes left
380 if ( ::GetLastError() != ERROR_BROKEN_PIPE
)
383 wxLogLastError(_T("PeekNamedPipe"));
386 // don't try to continue reading from a pipe if an error occurred or if
387 // it had been closed
388 ::CloseHandle(m_hInput
);
390 wxPipeInputStream
*self
= wxConstCast(this, wxPipeInputStream
);
392 self
->m_hInput
= INVALID_HANDLE_VALUE
;
393 self
->m_lasterror
= wxSTREAM_EOF
;
398 return nAvailable
!= 0;
401 size_t wxPipeInputStream::OnSysRead(void *buffer
, size_t len
)
405 m_lasterror
= wxSTREAM_EOF
;
411 if ( !::ReadFile(m_hInput
, buffer
, len
, &bytesRead
, NULL
) )
413 m_lasterror
= ::GetLastError() == ERROR_BROKEN_PIPE
415 : wxSTREAM_READ_ERROR
;
418 // bytesRead is set to 0, as desired, if an error occurred
422 // ----------------------------------------------------------------------------
423 // wxPipeOutputStream
424 // ----------------------------------------------------------------------------
426 wxPipeOutputStream::wxPipeOutputStream(HANDLE hOutput
)
430 // unblock the pipe to prevent deadlocks when we're writing to the pipe
431 // from which the child process can't read because it is writing in its own
433 DWORD mode
= PIPE_READMODE_BYTE
| PIPE_NOWAIT
;
434 if ( !::SetNamedPipeHandleState
438 NULL
, // collection count (we don't set it)
439 NULL
// timeout (we don't set it neither)
442 wxLogLastError(_T("SetNamedPipeHandleState(PIPE_NOWAIT)"));
446 bool wxPipeOutputStream::Close()
448 return ::CloseHandle(m_hOutput
) != 0;
452 size_t wxPipeOutputStream::OnSysWrite(const void *buffer
, size_t len
)
454 m_lasterror
= wxSTREAM_NO_ERROR
;
456 DWORD totalWritten
= 0;
460 if ( !::WriteFile(m_hOutput
, buffer
, len
, &chunkWritten
, NULL
) )
462 m_lasterror
= ::GetLastError() == ERROR_BROKEN_PIPE
464 : wxSTREAM_WRITE_ERROR
;
471 buffer
= (char *)buffer
+ chunkWritten
;
472 totalWritten
+= chunkWritten
;
479 #endif // wxUSE_STREAMS
481 // ============================================================================
482 // wxExecute functions family
483 // ============================================================================
487 // connect to the given server via DDE and ask it to execute the command
489 wxExecuteDDE(const wxString
& ddeServer
,
490 const wxString
& ddeTopic
,
491 const wxString
& ddeCommand
)
493 bool ok
wxDUMMY_INITIALIZE(false);
497 conn
= client
.MakeConnection(wxEmptyString
, ddeServer
, ddeTopic
);
502 else // connected to DDE server
504 // the added complication here is that although most programs use
505 // XTYP_EXECUTE for their DDE API, some important ones -- like Word
506 // and other MS stuff - use XTYP_REQUEST!
508 // moreover, anotheri mportant program (IE) understands both but
509 // returns an error from Execute() so we must try Request() first
510 // to avoid doing it twice
512 // we're prepared for this one to fail, so don't show errors
515 ok
= conn
->Request(ddeCommand
) != NULL
;
520 // now try execute -- but show the errors
521 ok
= conn
->Execute(ddeCommand
);
530 long wxExecute(const wxString
& cmd
, int flags
, wxProcess
*handler
)
532 wxCHECK_MSG( !cmd
.empty(), 0, wxT("empty command in wxExecute") );
535 // for many reasons, the code below breaks down if it's called from another
536 // thread -- this could be fixed, but as Unix versions don't support this
537 // neither I don't want to waste time on this now
538 wxASSERT_MSG( wxThread::IsMain(),
539 _T("wxExecute() can be called only from the main thread") );
540 #endif // wxUSE_THREADS
545 // DDE hack: this is really not pretty, but we need to allow this for
546 // transparent handling of DDE servers in wxMimeTypesManager. Usually it
547 // returns the command which should be run to view/open/... a file of the
548 // given type. Sometimes, however, this command just launches the server
549 // and an additional DDE request must be made to really open the file. To
550 // keep all this well hidden from the application, we allow a special form
551 // of command: WX_DDE#<command>#DDE_SERVER#DDE_TOPIC#DDE_COMMAND in which
552 // case we execute just <command> and process the rest below
553 wxString ddeServer
, ddeTopic
, ddeCommand
;
554 static const size_t lenDdePrefix
= 7; // strlen("WX_DDE:")
555 if ( cmd
.Left(lenDdePrefix
) == _T("WX_DDE#") )
557 // speed up the concatenations below
558 ddeServer
.reserve(256);
559 ddeTopic
.reserve(256);
560 ddeCommand
.reserve(256);
562 const wxChar
*p
= cmd
.c_str() + 7;
563 while ( *p
&& *p
!= _T('#') )
575 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
578 while ( *p
&& *p
!= _T('#') )
590 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
593 while ( *p
&& *p
!= _T('#') )
605 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
613 // if we want to just launch the program and not wait for its
614 // termination, try to execute DDE command right now, it can succeed if
615 // the process is already running - but as it fails if it's not
616 // running, suppress any errors it might generate
617 if ( !(flags
& wxEXEC_SYNC
) )
620 if ( wxExecuteDDE(ddeServer
, ddeTopic
, ddeCommand
) )
622 // a dummy PID - this is a hack, of course, but it's well worth
623 // it as we don't open a new server each time we're called
624 // which would be quite bad
636 // the IO redirection is only supported with wxUSE_STREAMS
637 BOOL redirect
= FALSE
;
639 #if wxUSE_STREAMS && !defined(__WXWINCE__)
640 wxPipe pipeIn
, pipeOut
, pipeErr
;
642 // we'll save here the copy of pipeIn[Write]
643 HANDLE hpipeStdinWrite
= INVALID_HANDLE_VALUE
;
645 // open the pipes to which child process IO will be redirected if needed
646 if ( handler
&& handler
->IsRedirected() )
648 // create pipes for redirecting stdin, stdout and stderr
649 if ( !pipeIn
.Create() || !pipeOut
.Create() || !pipeErr
.Create() )
651 wxLogSysError(_("Failed to redirect the child process IO"));
653 // indicate failure: we need to return different error code
654 // depending on the sync flag
655 return flags
& wxEXEC_SYNC
? -1 : 0;
660 #endif // wxUSE_STREAMS
662 // create the process
667 #if wxUSE_STREAMS && !defined(__WXWINCE__)
670 si
.dwFlags
= STARTF_USESTDHANDLES
;
672 si
.hStdInput
= pipeIn
[wxPipe::Read
];
673 si
.hStdOutput
= pipeOut
[wxPipe::Write
];
674 si
.hStdError
= pipeErr
[wxPipe::Write
];
676 // when the std IO is redirected, we don't show the (console) process
677 // window by default, but this can be overridden by the caller by
678 // specifying wxEXEC_NOHIDE flag
679 if ( !(flags
& wxEXEC_NOHIDE
) )
681 si
.dwFlags
|= STARTF_USESHOWWINDOW
;
682 si
.wShowWindow
= SW_HIDE
;
685 // we must duplicate the handle to the write side of stdin pipe to make
686 // it non inheritable: indeed, we must close the writing end of pipeIn
687 // before launching the child process as otherwise this handle will be
688 // inherited by the child which will never close it and so the pipe
689 // will never be closed and the child will be left stuck in ReadFile()
690 HANDLE pipeInWrite
= pipeIn
.Detach(wxPipe::Write
);
691 if ( !::DuplicateHandle
693 ::GetCurrentProcess(),
695 ::GetCurrentProcess(),
697 0, // desired access: unused here
698 FALSE
, // not inherited
699 DUPLICATE_SAME_ACCESS
// same access as for src handle
702 wxLogLastError(_T("DuplicateHandle"));
705 ::CloseHandle(pipeInWrite
);
707 #endif // wxUSE_STREAMS
709 PROCESS_INFORMATION pi
;
710 DWORD dwFlags
= CREATE_SUSPENDED
;
713 dwFlags
|= CREATE_DEFAULT_ERROR_MODE
;
715 // we are assuming commands without spaces for now
716 wxString moduleName
= command
.BeforeFirst(wxT(' '));
717 wxString arguments
= command
.AfterFirst(wxT(' '));
720 bool ok
= ::CreateProcess
722 // WinCE requires appname to be non null
723 // Win32 allows for null
726 moduleName
.wx_str(),// application name
728 arguments
.wx_str(), // arguments
730 NULL
, // application name (use only cmd line)
732 command
.wx_str(), // full command line
734 NULL
, // security attributes: defaults for both
735 NULL
, // the process and its main thread
736 redirect
, // inherit handles if we use pipes
737 dwFlags
, // process creation flags
738 NULL
, // environment (use the same)
739 NULL
, // current directory (use the same)
740 &si
, // startup info (unused here)
744 #if wxUSE_STREAMS && !defined(__WXWINCE__)
745 // we can close the pipe ends used by child anyhow
748 ::CloseHandle(pipeIn
.Detach(wxPipe::Read
));
749 ::CloseHandle(pipeOut
.Detach(wxPipe::Write
));
750 ::CloseHandle(pipeErr
.Detach(wxPipe::Write
));
752 #endif // wxUSE_STREAMS
756 #if wxUSE_STREAMS && !defined(__WXWINCE__)
757 // close the other handles too
760 ::CloseHandle(pipeOut
.Detach(wxPipe::Read
));
761 ::CloseHandle(pipeErr
.Detach(wxPipe::Read
));
763 #endif // wxUSE_STREAMS
765 wxLogSysError(_("Execution of command '%s' failed"), command
.c_str());
767 return flags
& wxEXEC_SYNC
? -1 : 0;
770 #if wxUSE_STREAMS && !defined(__WXWINCE__)
771 // the input buffer bufOut is connected to stdout, this is why it is
772 // called bufOut and not bufIn
773 wxStreamTempInputBuffer bufOut
,
778 // We can now initialize the wxStreams
780 outStream
= new wxPipeInputStream(pipeOut
.Detach(wxPipe::Read
));
782 errStream
= new wxPipeInputStream(pipeErr
.Detach(wxPipe::Read
));
784 inStream
= new wxPipeOutputStream(hpipeStdinWrite
);
786 handler
->SetPipeStreams(outStream
, inStream
, errStream
);
788 bufOut
.Init(outStream
);
789 bufErr
.Init(errStream
);
791 #endif // wxUSE_STREAMS
793 // create a hidden window to receive notification about process
795 HWND hwnd
= wxCreateHiddenWindow
797 &gs_classForHiddenWindow
,
798 wxMSWEXEC_WNDCLASSNAME
,
799 (WNDPROC
)wxExecuteWindowCbk
802 wxASSERT_MSG( hwnd
, wxT("can't create a hidden window for wxExecute") );
805 wxExecuteData
*data
= new wxExecuteData
;
806 data
->hProcess
= pi
.hProcess
;
807 data
->dwProcessId
= pi
.dwProcessId
;
809 data
->state
= (flags
& wxEXEC_SYNC
) != 0;
810 if ( flags
& wxEXEC_SYNC
)
812 // handler may be !NULL for capturing program output, but we don't use
813 // it wxExecuteData struct in this case
814 data
->handler
= NULL
;
818 // may be NULL or not
819 data
->handler
= handler
;
823 HANDLE hThread
= ::CreateThread(NULL
,
830 // resume process we created now - whether the thread creation succeeded or
832 if ( ::ResumeThread(pi
.hThread
) == (DWORD
)-1 )
834 // ignore it - what can we do?
835 wxLogLastError(wxT("ResumeThread in wxExecute"));
838 // close unneeded handle
839 if ( !::CloseHandle(pi
.hThread
) )
840 wxLogLastError(wxT("CloseHandle(hThread)"));
844 wxLogLastError(wxT("CreateThread in wxExecute"));
849 // the process still started up successfully...
850 return pi
.dwProcessId
;
853 ::CloseHandle(hThread
);
855 #if wxUSE_IPC && !defined(__WXWINCE__)
856 // second part of DDE hack: now establish the DDE conversation with the
857 // just launched process
858 if ( !ddeServer
.empty() )
862 // give the process the time to init itself
864 // we use a very big timeout hoping that WaitForInputIdle() will return
865 // much sooner, but not INFINITE just in case the process hangs
866 // completely - like this we will regain control sooner or later
867 switch ( ::WaitForInputIdle(pi
.hProcess
, 10000 /* 10 seconds */) )
870 wxFAIL_MSG( _T("unexpected WaitForInputIdle() return code") );
874 wxLogLastError(_T("WaitForInputIdle() in wxExecute"));
877 wxLogDebug(_T("Timeout too small in WaitForInputIdle"));
883 // ok, process ready to accept DDE requests
884 ok
= wxExecuteDDE(ddeServer
, ddeTopic
, ddeCommand
);
889 wxLogDebug(_T("Failed to send DDE request to the process \"%s\"."),
895 if ( !(flags
& wxEXEC_SYNC
) )
897 // clean up will be done when the process terminates
900 return pi
.dwProcessId
;
903 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
904 wxCHECK_MSG( traits
, -1, _T("no wxAppTraits in wxExecute()?") );
907 if ( !(flags
& wxEXEC_NODISABLE
) )
909 // disable all app windows while waiting for the child process to finish
910 cookie
= traits
->BeforeChildWaitLoop();
913 // wait until the child process terminates
914 while ( data
->state
)
916 #if wxUSE_STREAMS && !defined(__WXWINCE__)
919 #endif // wxUSE_STREAMS
921 // don't eat 100% of the CPU -- ugly but anything else requires
922 // real async IO which we don't have for the moment
925 // we must process messages or we'd never get wxWM_PROC_TERMINATED
926 traits
->AlwaysYield();
929 if ( !(flags
& wxEXEC_NODISABLE
) )
931 // reenable disabled windows back
932 traits
->AfterChildWaitLoop(cookie
);
935 DWORD dwExitCode
= data
->dwExitCode
;
938 // return the exit code
942 long wxExecute(wxChar
**argv
, int flags
, wxProcess
*handler
)
955 return wxExecute(command
, flags
, handler
);