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 license
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
21 #pragma implementation
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
36 #if wxUSE_GUI // See 'dirty hack' below.
42 #include "wx/stream.h"
43 #include "wx/process.h"
46 #include "wx/msw/private.h"
50 #if !defined(__GNUWIN32__) && !defined(__WXWINE__) && !defined(__SALFORDC__) && !defined(__WXMICROWIN__)
57 #if defined(__GNUWIN32__) && !defined(__TWIN32__)
58 #include <sys/unistd.h>
62 #if defined(__WIN32__) && !defined(__WXWINE__) && !defined(__WXMICROWIN__)
74 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
81 #include "wx/dde.h" // for WX_DDE hack in wxExecute
84 // ----------------------------------------------------------------------------
86 // ----------------------------------------------------------------------------
88 // this message is sent when the process we're waiting for terminates
89 #define wxWM_PROC_TERMINATED (WM_USER + 10000)
91 // ----------------------------------------------------------------------------
92 // this module globals
93 // ----------------------------------------------------------------------------
95 // we need to create a hidden window to receive the process termination
96 // notifications and for this we need a (Win) class name for it which we will
97 // register the first time it's needed
98 static const wxChar
*gs_classForHiddenWindow
= NULL
;
100 // ----------------------------------------------------------------------------
102 // ----------------------------------------------------------------------------
104 // structure describing the process we're being waiting for
111 if ( !::CloseHandle(hProcess
) )
113 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 #if defined(__WIN32__) && wxUSE_STREAMS
128 // ----------------------------------------------------------------------------
130 // ----------------------------------------------------------------------------
132 class wxPipeInputStream
: public wxInputStream
135 wxPipeInputStream(HANDLE hInput
);
136 virtual ~wxPipeInputStream();
138 // returns TRUE if the pipe is still opened
139 bool IsOpened() const { return m_hInput
!= INVALID_HANDLE_VALUE
; }
141 // returns TRUE if there is any data to be read from the pipe
142 virtual bool CanRead() const;
145 size_t OnSysRead(void *buffer
, size_t len
);
150 DECLARE_NO_COPY_CLASS(wxPipeInputStream
)
153 class wxPipeOutputStream
: public wxOutputStream
156 wxPipeOutputStream(HANDLE hOutput
);
157 virtual ~wxPipeOutputStream();
160 size_t OnSysWrite(const void *buffer
, size_t len
);
165 DECLARE_NO_COPY_CLASS(wxPipeOutputStream
)
168 // define this to let wxexec.cpp know that we know what we're doing
169 #define _WX_USED_BY_WXEXECUTE_
170 #include "../common/execcmn.cpp"
172 // ----------------------------------------------------------------------------
173 // wxPipe represents a Win32 anonymous pipe
174 // ----------------------------------------------------------------------------
179 // the symbolic names for the pipe ends
186 // default ctor doesn't do anything
187 wxPipe() { m_handles
[Read
] = m_handles
[Write
] = INVALID_HANDLE_VALUE
; }
189 // create the pipe, return TRUE if ok, FALSE on error
192 // default secutiry attributes
193 SECURITY_ATTRIBUTES security
;
195 security
.nLength
= sizeof(security
);
196 security
.lpSecurityDescriptor
= NULL
;
197 security
.bInheritHandle
= TRUE
; // to pass it to the child
199 if ( !::CreatePipe(&m_handles
[0], &m_handles
[1], &security
, 0) )
201 wxLogSysError(_("Failed to create an anonymous pipe"));
209 // return TRUE if we were created successfully
210 bool IsOk() const { return m_handles
[Read
] != INVALID_HANDLE_VALUE
; }
212 // return the descriptor for one of the pipe ends
213 HANDLE
operator[](Direction which
) const
215 wxASSERT_MSG( which
>= 0 && (size_t)which
< WXSIZEOF(m_handles
),
216 _T("invalid pipe index") );
218 return m_handles
[which
];
221 // detach a descriptor, meaning that the pipe dtor won't close it, and
223 HANDLE
Detach(Direction which
)
225 wxASSERT_MSG( which
>= 0 && (size_t)which
< WXSIZEOF(m_handles
),
226 _T("invalid pipe index") );
228 HANDLE handle
= m_handles
[which
];
229 m_handles
[which
] = INVALID_HANDLE_VALUE
;
234 // close the pipe descriptors
237 for ( size_t n
= 0; n
< WXSIZEOF(m_handles
); n
++ )
239 if ( m_handles
[n
] != INVALID_HANDLE_VALUE
)
241 ::CloseHandle(m_handles
[n
]);
242 m_handles
[n
] = INVALID_HANDLE_VALUE
;
247 // dtor closes the pipe descriptors
248 ~wxPipe() { Close(); }
254 #endif // wxUSE_STREAMS
256 // ============================================================================
258 // ============================================================================
262 // ----------------------------------------------------------------------------
263 // process termination detecting support
264 // ----------------------------------------------------------------------------
266 // thread function for the thread monitoring the process termination
267 static DWORD __stdcall
wxExecuteThread(void *arg
)
269 wxExecuteData
* const data
= (wxExecuteData
*)arg
;
271 if ( ::WaitForSingleObject(data
->hProcess
, INFINITE
) != WAIT_OBJECT_0
)
273 wxLogDebug(_T("Waiting for the process termination failed!"));
277 if ( !::GetExitCodeProcess(data
->hProcess
, &data
->dwExitCode
) )
279 wxLogLastError(wxT("GetExitCodeProcess"));
282 wxASSERT_MSG( data
->dwExitCode
!= STILL_ACTIVE
,
283 wxT("process should have terminated") );
285 // send a message indicating process termination to the window
286 ::SendMessage(data
->hWnd
, wxWM_PROC_TERMINATED
, 0, (LPARAM
)data
);
291 // window procedure of a hidden window which is created just to receive
292 // the notification message when a process exits
293 LRESULT APIENTRY _EXPORT
wxExecuteWindowCbk(HWND hWnd
, UINT message
,
294 WPARAM wParam
, LPARAM lParam
)
296 if ( message
== wxWM_PROC_TERMINATED
)
298 DestroyWindow(hWnd
); // we don't need it any more
300 wxExecuteData
* const data
= (wxExecuteData
*)lParam
;
303 data
->handler
->OnTerminate((int)data
->dwProcessId
,
304 (int)data
->dwExitCode
);
309 // we're executing synchronously, tell the waiting thread
310 // that the process finished
315 // asynchronous execution - we should do the clean up
323 return ::DefWindowProc(hWnd
, message
, wParam
, lParam
);
327 // ============================================================================
328 // implementation of IO redirection support classes
329 // ============================================================================
333 // ----------------------------------------------------------------------------
334 // wxPipeInputStreams
335 // ----------------------------------------------------------------------------
337 wxPipeInputStream::wxPipeInputStream(HANDLE hInput
)
342 wxPipeInputStream::~wxPipeInputStream()
344 if ( m_hInput
!= INVALID_HANDLE_VALUE
)
345 ::CloseHandle(m_hInput
);
348 bool wxPipeInputStream::CanRead() const
359 // function name is misleading, it works with anon pipes as well
360 DWORD rc
= ::PeekNamedPipe
363 NULL
, 0, // ptr to buffer and its size
364 NULL
, // [out] bytes read
365 &nAvailable
, // [out] bytes available
366 NULL
// [out] bytes left
371 if ( ::GetLastError() != ERROR_BROKEN_PIPE
)
374 wxLogLastError(_T("PeekNamedPipe"));
377 // don't try to continue reading from a pipe if an error occured or if
378 // it had been closed
379 ::CloseHandle(m_hInput
);
381 wxPipeInputStream
*self
= wxConstCast(this, wxPipeInputStream
);
383 self
->m_hInput
= INVALID_HANDLE_VALUE
;
384 self
->m_lasterror
= wxSTREAM_EOF
;
389 return nAvailable
!= 0;
393 size_t wxPipeInputStream::OnSysRead(void *buffer
, size_t len
)
397 m_lasterror
= wxSTREAM_EOF
;
403 if ( !::ReadFile(m_hInput
, buffer
, len
, &bytesRead
, NULL
) )
405 m_lasterror
= ::GetLastError() == ERROR_BROKEN_PIPE
407 : wxSTREAM_READ_ERROR
;
410 // bytesRead is set to 0, as desired, if an error occured
414 // ----------------------------------------------------------------------------
415 // wxPipeOutputStream
416 // ----------------------------------------------------------------------------
418 wxPipeOutputStream::wxPipeOutputStream(HANDLE hOutput
)
423 wxPipeOutputStream::~wxPipeOutputStream()
425 ::CloseHandle(m_hOutput
);
428 size_t wxPipeOutputStream::OnSysWrite(const void *buffer
, size_t len
)
432 m_lasterror
= wxSTREAM_NO_ERROR
;
433 if ( !::WriteFile(m_hOutput
, buffer
, len
, &bytesWritten
, NULL
) )
435 m_lasterror
= ::GetLastError() == ERROR_BROKEN_PIPE
437 : wxSTREAM_WRITE_ERROR
;
443 #endif // wxUSE_STREAMS
447 // ============================================================================
448 // wxExecute functions family
449 // ============================================================================
453 // connect to the given server via DDE and ask it to execute the command
454 static bool wxExecuteDDE(const wxString
& ddeServer
,
455 const wxString
& ddeTopic
,
456 const wxString
& ddeCommand
)
461 wxConnectionBase
*conn
= client
.MakeConnection(_T(""),
468 else // connected to DDE server
470 // the added complication here is that although most
471 // programs use XTYP_EXECUTE for their DDE API, some
472 // important ones - like IE and other MS stuff - use
475 // so we try one first and then the other one if it
479 ok
= conn
->Execute(ddeCommand
);
484 // now try request - but show the errors
485 ok
= conn
->Request(ddeCommand
) != NULL
;
494 long wxExecute(const wxString
& cmd
, int flags
, wxProcess
*handler
)
496 wxCHECK_MSG( !!cmd
, 0, wxT("empty command in wxExecute") );
501 // DDE hack: this is really not pretty, but we need to allow this for
502 // transparent handling of DDE servers in wxMimeTypesManager. Usually it
503 // returns the command which should be run to view/open/... a file of the
504 // given type. Sometimes, however, this command just launches the server
505 // and an additional DDE request must be made to really open the file. To
506 // keep all this well hidden from the application, we allow a special form
507 // of command: WX_DDE#<command>#DDE_SERVER#DDE_TOPIC#DDE_COMMAND in which
508 // case we execute just <command> and process the rest below
509 wxString ddeServer
, ddeTopic
, ddeCommand
;
510 static const size_t lenDdePrefix
= 7; // strlen("WX_DDE:")
511 if ( cmd
.Left(lenDdePrefix
) == _T("WX_DDE#") )
513 // speed up the concatenations below
514 ddeServer
.reserve(256);
515 ddeTopic
.reserve(256);
516 ddeCommand
.reserve(256);
518 const wxChar
*p
= cmd
.c_str() + 7;
519 while ( *p
&& *p
!= _T('#') )
531 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
534 while ( *p
&& *p
!= _T('#') )
546 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
549 while ( *p
&& *p
!= _T('#') )
561 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
569 // if we want to just launch the program and not wait for its
570 // termination, try to execute DDE command right now, it can succeed if
571 // the process is already running - but as it fails if it's not
572 // running, suppress any errors it might generate
573 if ( !(flags
& wxEXEC_SYNC
) )
576 if ( wxExecuteDDE(ddeServer
, ddeTopic
, ddeCommand
) )
578 // a dummy PID - this is a hack, of course, but it's well worth
579 // it as we don't open a new server each time we're called
580 // which would be quite bad
592 #if defined(__WIN32__) && !defined(__TWIN32__)
594 // the IO redirection is only supported with wxUSE_STREAMS
595 BOOL redirect
= FALSE
;
598 wxPipe pipeIn
, pipeOut
, pipeErr
;
600 // we'll save here the copy of pipeIn[Write]
601 HANDLE hpipeStdinWrite
= INVALID_HANDLE_VALUE
;
603 // open the pipes to which child process IO will be redirected if needed
604 if ( handler
&& handler
->IsRedirected() )
606 // create pipes for redirecting stdin, stdout and stderr
607 if ( !pipeIn
.Create() || !pipeOut
.Create() || !pipeErr
.Create() )
609 wxLogSysError(_("Failed to redirect the child process IO"));
611 // indicate failure: we need to return different error code
612 // depending on the sync flag
613 return flags
& wxEXEC_SYNC
? -1 : 0;
618 #endif // wxUSE_STREAMS
620 // create the process
628 si
.dwFlags
= STARTF_USESTDHANDLES
;
630 si
.hStdInput
= pipeIn
[wxPipe::Read
];
631 si
.hStdOutput
= pipeOut
[wxPipe::Write
];
632 si
.hStdError
= pipeErr
[wxPipe::Write
];
634 // when the std IO is redirected, we don't show the (console) process
635 // window by default, but this can be overridden by the caller by
636 // specifying wxEXEC_NOHIDE flag
637 if ( !(flags
& wxEXEC_NOHIDE
) )
639 si
.dwFlags
|= STARTF_USESHOWWINDOW
;
640 si
.wShowWindow
= SW_HIDE
;
643 // we must duplicate the handle to the write side of stdin pipe to make
644 // it non inheritable: indeed, we must close the writing end of pipeIn
645 // before launching the child process as otherwise this handle will be
646 // inherited by the child which will never close it and so the pipe
647 // will never be closed and the child will be left stuck in ReadFile()
648 HANDLE pipeInWrite
= pipeIn
.Detach(wxPipe::Write
);
649 if ( !::DuplicateHandle
651 ::GetCurrentProcess(),
653 ::GetCurrentProcess(),
655 0, // desired access: unused here
656 FALSE
, // not inherited
657 DUPLICATE_SAME_ACCESS
// same access as for src handle
660 wxLogLastError(_T("DuplicateHandle"));
663 ::CloseHandle(pipeInWrite
);
665 #endif // wxUSE_STREAMS
667 PROCESS_INFORMATION pi
;
668 DWORD dwFlags
= CREATE_DEFAULT_ERROR_MODE
| CREATE_SUSPENDED
;
670 bool ok
= ::CreateProcess
672 NULL
, // application name (use only cmd line)
674 command
.c_str(), // full command line
675 NULL
, // security attributes: defaults for both
676 NULL
, // the process and its main thread
677 redirect
, // inherit handles if we use pipes
678 dwFlags
, // process creation flags
679 NULL
, // environment (use the same)
680 NULL
, // current directory (use the same)
681 &si
, // startup info (unused here)
686 // we can close the pipe ends used by child anyhow
689 ::CloseHandle(pipeIn
.Detach(wxPipe::Read
));
690 ::CloseHandle(pipeOut
.Detach(wxPipe::Write
));
691 ::CloseHandle(pipeErr
.Detach(wxPipe::Write
));
693 #endif // wxUSE_STREAMS
698 // close the other handles too
701 ::CloseHandle(pipeOut
.Detach(wxPipe::Read
));
702 ::CloseHandle(pipeErr
.Detach(wxPipe::Read
));
704 #endif // wxUSE_STREAMS
706 wxLogSysError(_("Execution of command '%s' failed"), command
.c_str());
708 return flags
& wxEXEC_SYNC
? -1 : 0;
712 // the input buffer bufOut is connected to stdout, this is why it is
713 // called bufOut and not bufIn
714 wxStreamTempInputBuffer bufOut
,
719 // We can now initialize the wxStreams
721 outStream
= new wxPipeInputStream(pipeOut
.Detach(wxPipe::Read
));
723 errStream
= new wxPipeInputStream(pipeErr
.Detach(wxPipe::Read
));
725 inStream
= new wxPipeOutputStream(hpipeStdinWrite
);
727 handler
->SetPipeStreams(outStream
, inStream
, errStream
);
729 bufOut
.Init(outStream
);
730 bufErr
.Init(errStream
);
732 #endif // wxUSE_STREAMS
734 // register the class for the hidden window used for the notifications
735 if ( !gs_classForHiddenWindow
)
737 gs_classForHiddenWindow
= _T("wxHiddenWindow");
740 wxZeroMemory(wndclass
);
741 wndclass
.lpfnWndProc
= (WNDPROC
)wxExecuteWindowCbk
;
742 wndclass
.hInstance
= wxGetInstance();
743 wndclass
.lpszClassName
= gs_classForHiddenWindow
;
745 if ( !::RegisterClass(&wndclass
) )
747 wxLogLastError(wxT("RegisterClass(hidden window)"));
751 // create a hidden window to receive notification about process
753 HWND hwnd
= ::CreateWindow(gs_classForHiddenWindow
, NULL
,
756 (HMENU
)NULL
, wxGetInstance(), 0);
757 wxASSERT_MSG( hwnd
, wxT("can't create a hidden window for wxExecute") );
760 wxExecuteData
*data
= new wxExecuteData
;
761 data
->hProcess
= pi
.hProcess
;
762 data
->dwProcessId
= pi
.dwProcessId
;
764 data
->state
= (flags
& wxEXEC_SYNC
) != 0;
765 if ( flags
& wxEXEC_SYNC
)
767 // handler may be !NULL for capturing program output, but we don't use
768 // it wxExecuteData struct in this case
769 data
->handler
= NULL
;
773 // may be NULL or not
774 data
->handler
= handler
;
778 HANDLE hThread
= ::CreateThread(NULL
,
785 // resume process we created now - whether the thread creation succeeded or
787 if ( ::ResumeThread(pi
.hThread
) == (DWORD
)-1 )
789 // ignore it - what can we do?
790 wxLogLastError(wxT("ResumeThread in wxExecute"));
793 // close unneeded handle
794 if ( !::CloseHandle(pi
.hThread
) )
795 wxLogLastError(wxT("CloseHandle(hThread)"));
799 wxLogLastError(wxT("CreateThread in wxExecute"));
804 // the process still started up successfully...
805 return pi
.dwProcessId
;
808 ::CloseHandle(hThread
);
811 // second part of DDE hack: now establish the DDE conversation with the
812 // just launched process
813 if ( !ddeServer
.empty() )
817 // give the process the time to init itself
819 // we use a very big timeout hoping that WaitForInputIdle() will return
820 // much sooner, but not INFINITE just in case the process hangs
821 // completely - like this we will regain control sooner or later
822 switch ( ::WaitForInputIdle(pi
.hProcess
, 10000 /* 10 seconds */) )
825 wxFAIL_MSG( _T("unexpected WaitForInputIdle() return code") );
829 wxLogLastError(_T("WaitForInputIdle() in wxExecute"));
832 wxLogDebug(_T("Timeout too small in WaitForInputIdle"));
838 // ok, process ready to accept DDE requests
839 ok
= wxExecuteDDE(ddeServer
, ddeTopic
, ddeCommand
);
844 if ( !(flags
& wxEXEC_SYNC
) )
846 // clean up will be done when the process terminates
849 return pi
.dwProcessId
;
852 // disable all app windows while waiting for the child process to finish
856 We use a dirty hack here to disable all application windows (which we
857 must do because otherwise the calls to wxYield() could lead to some very
858 unexpected reentrancies in the users code) but to avoid losing
859 focus/activation entirely when the child process terminates which would
860 happen if we simply disabled everything using wxWindowDisabler. Indeed,
861 remember that Windows will never activate a disabled window and when the
862 last childs window is closed and Windows looks for a window to activate
863 all our windows are still disabled. There is no way to enable them in
864 time because we don't know when the childs windows are going to be
865 closed, so the solution we use here is to keep one special tiny frame
866 enabled all the time. Then when the child terminates it will get
867 activated and when we close it below -- after reenabling all the other
868 windows! -- the previously active window becomes activated again and
875 // first disable all existing windows
878 // then create an "invisible" frame: it has minimal size, is positioned
879 // (hopefully) outside the screen and doesn't appear on the taskbar
880 winActive
= new wxFrame
882 wxTheApp
->GetTopWindow(),
885 wxPoint(32600, 32600),
887 wxDEFAULT_FRAME_STYLE
| wxFRAME_NO_TASKBAR
892 // wait until the child process terminates
893 while ( data
->state
)
898 #endif // wxUSE_STREAMS
900 // don't eat 100% of the CPU -- ugly but anything else requires
901 // real async IO which we don't have for the moment
908 // dispatch the messages to the hidden window so that it could
909 // process the wxWM_PROC_TERMINATED notification
911 ::PeekMessage(&msg
, hwnd
, 0, 0, PM_REMOVE
);
918 // finally delete the dummy frame and, as wd has been already destroyed and
919 // the other windows reenabled, the activation is going to return to the
920 // window which had it before
921 winActive
->Destroy();
924 DWORD dwExitCode
= data
->dwExitCode
;
927 // return the exit code
930 long instanceID
= WinExec((LPCSTR
) WXSTRINGCAST command
, SW_SHOW
);
932 return flags
& wxEXEC_SYNC
? -1 : 0;
934 if ( flags
& wxEXEC_SYNC
)
940 running
= GetModuleUsage((HINSTANCE
)instanceID
);
948 long wxExecute(wxChar
**argv
, int flags
, wxProcess
*handler
)
961 return wxExecute(command
, flags
, handler
);