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
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
117 if ( !::CloseHandle(hProcess
) )
119 wxLogLastError(wxT("CloseHandle(hProcess)"));
124 HWND hWnd
; // window to send wxWM_PROC_TERMINATED to
125 HANDLE hProcess
; // handle of the process
126 DWORD dwProcessId
; // pid of the process
128 DWORD dwExitCode
; // the exit code of the process
129 bool state
; // set to FALSE when the process finishes
132 class wxExecuteModule
: public wxModule
135 virtual bool OnInit() { return true; }
136 virtual void OnExit()
138 if ( *gs_classForHiddenWindow
)
140 if ( !::UnregisterClass(wxMSWEXEC_WNDCLASSNAME
, wxGetInstance()) )
142 wxLogLastError(_T("UnregisterClass(wxExecClass)"));
145 gs_classForHiddenWindow
= NULL
;
150 DECLARE_DYNAMIC_CLASS(wxExecuteModule
)
153 #if wxUSE_STREAMS && !defined(__WXWINCE__)
155 // ----------------------------------------------------------------------------
157 // ----------------------------------------------------------------------------
159 class wxPipeInputStream
: public wxInputStream
162 wxPipeInputStream(HANDLE hInput
);
163 virtual ~wxPipeInputStream();
165 // returns TRUE if the pipe is still opened
166 bool IsOpened() const { return m_hInput
!= INVALID_HANDLE_VALUE
; }
168 // returns TRUE if there is any data to be read from the pipe
169 virtual bool CanRead() const;
172 size_t OnSysRead(void *buffer
, size_t len
);
177 DECLARE_NO_COPY_CLASS(wxPipeInputStream
)
180 class wxPipeOutputStream
: public wxOutputStream
183 wxPipeOutputStream(HANDLE hOutput
);
184 virtual ~wxPipeOutputStream();
187 size_t OnSysWrite(const void *buffer
, size_t len
);
192 DECLARE_NO_COPY_CLASS(wxPipeOutputStream
)
195 // define this to let wxexec.cpp know that we know what we're doing
196 #define _WX_USED_BY_WXEXECUTE_
197 #include "../common/execcmn.cpp"
199 // ----------------------------------------------------------------------------
200 // wxPipe represents a Win32 anonymous pipe
201 // ----------------------------------------------------------------------------
206 // the symbolic names for the pipe ends
213 // default ctor doesn't do anything
214 wxPipe() { m_handles
[Read
] = m_handles
[Write
] = INVALID_HANDLE_VALUE
; }
216 // create the pipe, return TRUE if ok, FALSE on error
219 // default secutiry attributes
220 SECURITY_ATTRIBUTES security
;
222 security
.nLength
= sizeof(security
);
223 security
.lpSecurityDescriptor
= NULL
;
224 security
.bInheritHandle
= TRUE
; // to pass it to the child
226 if ( !::CreatePipe(&m_handles
[0], &m_handles
[1], &security
, 0) )
228 wxLogSysError(_("Failed to create an anonymous pipe"));
236 // return TRUE if we were created successfully
237 bool IsOk() const { return m_handles
[Read
] != INVALID_HANDLE_VALUE
; }
239 // return the descriptor for one of the pipe ends
240 HANDLE
operator[](Direction which
) const
242 wxASSERT_MSG( which
>= 0 && (size_t)which
< WXSIZEOF(m_handles
),
243 _T("invalid pipe index") );
245 return m_handles
[which
];
248 // detach a descriptor, meaning that the pipe dtor won't close it, and
250 HANDLE
Detach(Direction which
)
252 wxASSERT_MSG( which
>= 0 && (size_t)which
< WXSIZEOF(m_handles
),
253 _T("invalid pipe index") );
255 HANDLE handle
= m_handles
[which
];
256 m_handles
[which
] = INVALID_HANDLE_VALUE
;
261 // close the pipe descriptors
264 for ( size_t n
= 0; n
< WXSIZEOF(m_handles
); n
++ )
266 if ( m_handles
[n
] != INVALID_HANDLE_VALUE
)
268 ::CloseHandle(m_handles
[n
]);
269 m_handles
[n
] = INVALID_HANDLE_VALUE
;
274 // dtor closes the pipe descriptors
275 ~wxPipe() { Close(); }
281 #endif // wxUSE_STREAMS
283 // ============================================================================
285 // ============================================================================
287 // ----------------------------------------------------------------------------
288 // process termination detecting support
289 // ----------------------------------------------------------------------------
291 // thread function for the thread monitoring the process termination
292 static DWORD __stdcall
wxExecuteThread(void *arg
)
294 wxExecuteData
* const data
= (wxExecuteData
*)arg
;
296 if ( ::WaitForSingleObject(data
->hProcess
, INFINITE
) != WAIT_OBJECT_0
)
298 wxLogDebug(_T("Waiting for the process termination failed!"));
302 if ( !::GetExitCodeProcess(data
->hProcess
, &data
->dwExitCode
) )
304 wxLogLastError(wxT("GetExitCodeProcess"));
307 wxASSERT_MSG( data
->dwExitCode
!= STILL_ACTIVE
,
308 wxT("process should have terminated") );
310 // send a message indicating process termination to the window
311 ::SendMessage(data
->hWnd
, wxWM_PROC_TERMINATED
, 0, (LPARAM
)data
);
316 // window procedure of a hidden window which is created just to receive
317 // the notification message when a process exits
318 LRESULT APIENTRY _EXPORT
wxExecuteWindowCbk(HWND hWnd
, UINT message
,
319 WPARAM wParam
, LPARAM lParam
)
321 if ( message
== wxWM_PROC_TERMINATED
)
323 DestroyWindow(hWnd
); // we don't need it any more
325 wxExecuteData
* const data
= (wxExecuteData
*)lParam
;
328 data
->handler
->OnTerminate((int)data
->dwProcessId
,
329 (int)data
->dwExitCode
);
334 // we're executing synchronously, tell the waiting thread
335 // that the process finished
340 // asynchronous execution - we should do the clean up
348 return ::DefWindowProc(hWnd
, message
, wParam
, lParam
);
352 // ============================================================================
353 // implementation of IO redirection support classes
354 // ============================================================================
356 #if wxUSE_STREAMS && !defined(__WXWINCE__)
358 // ----------------------------------------------------------------------------
359 // wxPipeInputStreams
360 // ----------------------------------------------------------------------------
362 wxPipeInputStream::wxPipeInputStream(HANDLE hInput
)
367 wxPipeInputStream::~wxPipeInputStream()
369 if ( m_hInput
!= INVALID_HANDLE_VALUE
)
370 ::CloseHandle(m_hInput
);
373 bool wxPipeInputStream::CanRead() const
380 // function name is misleading, it works with anon pipes as well
381 DWORD rc
= ::PeekNamedPipe
384 NULL
, 0, // ptr to buffer and its size
385 NULL
, // [out] bytes read
386 &nAvailable
, // [out] bytes available
387 NULL
// [out] bytes left
392 if ( ::GetLastError() != ERROR_BROKEN_PIPE
)
395 wxLogLastError(_T("PeekNamedPipe"));
398 // don't try to continue reading from a pipe if an error occured or if
399 // it had been closed
400 ::CloseHandle(m_hInput
);
402 wxPipeInputStream
*self
= wxConstCast(this, wxPipeInputStream
);
404 self
->m_hInput
= INVALID_HANDLE_VALUE
;
405 self
->m_lasterror
= wxSTREAM_EOF
;
410 return nAvailable
!= 0;
413 size_t wxPipeInputStream::OnSysRead(void *buffer
, size_t len
)
417 m_lasterror
= wxSTREAM_EOF
;
423 if ( !::ReadFile(m_hInput
, buffer
, len
, &bytesRead
, NULL
) )
425 m_lasterror
= ::GetLastError() == ERROR_BROKEN_PIPE
427 : wxSTREAM_READ_ERROR
;
430 // bytesRead is set to 0, as desired, if an error occured
434 // ----------------------------------------------------------------------------
435 // wxPipeOutputStream
436 // ----------------------------------------------------------------------------
438 wxPipeOutputStream::wxPipeOutputStream(HANDLE hOutput
)
443 wxPipeOutputStream::~wxPipeOutputStream()
445 ::CloseHandle(m_hOutput
);
448 size_t wxPipeOutputStream::OnSysWrite(const void *buffer
, size_t len
)
452 m_lasterror
= wxSTREAM_NO_ERROR
;
453 if ( !::WriteFile(m_hOutput
, buffer
, len
, &bytesWritten
, NULL
) )
455 m_lasterror
= ::GetLastError() == ERROR_BROKEN_PIPE
457 : wxSTREAM_WRITE_ERROR
;
463 #endif // wxUSE_STREAMS
465 // ============================================================================
466 // wxExecute functions family
467 // ============================================================================
471 // connect to the given server via DDE and ask it to execute the command
472 static bool wxExecuteDDE(const wxString
& ddeServer
,
473 const wxString
& ddeTopic
,
474 const wxString
& ddeCommand
)
479 wxConnectionBase
*conn
= client
.MakeConnection(wxEmptyString
,
486 else // connected to DDE server
488 // the added complication here is that although most programs use
489 // XTYP_EXECUTE for their DDE API, some important ones -- like Word
490 // and other MS stuff - use XTYP_REQUEST!
492 // moreover, anotheri mportant program (IE) understands both but
493 // returns an error from Execute() so we must try Request() first
494 // to avoid doing it twice
496 // we're prepared for this one to fail, so don't show errors
499 ok
= conn
->Request(ddeCommand
) != NULL
;
504 // now try execute -- but show the errors
505 ok
= conn
->Execute(ddeCommand
);
514 long wxExecute(const wxString
& cmd
, int flags
, wxProcess
*handler
)
516 wxCHECK_MSG( !!cmd
, 0, wxT("empty command in wxExecute") );
519 // for many reasons, the code below breaks down if it's called from another
520 // thread -- this could be fixed, but as Unix versions don't support this
521 // neither I don't want to waste time on this now
522 wxASSERT_MSG( wxThread::IsMain(),
523 _T("wxExecute() can be called only from the main thread") );
524 #endif // wxUSE_THREADS
529 // DDE hack: this is really not pretty, but we need to allow this for
530 // transparent handling of DDE servers in wxMimeTypesManager. Usually it
531 // returns the command which should be run to view/open/... a file of the
532 // given type. Sometimes, however, this command just launches the server
533 // and an additional DDE request must be made to really open the file. To
534 // keep all this well hidden from the application, we allow a special form
535 // of command: WX_DDE#<command>#DDE_SERVER#DDE_TOPIC#DDE_COMMAND in which
536 // case we execute just <command> and process the rest below
537 wxString ddeServer
, ddeTopic
, ddeCommand
;
538 static const size_t lenDdePrefix
= 7; // strlen("WX_DDE:")
539 if ( cmd
.Left(lenDdePrefix
) == _T("WX_DDE#") )
541 // speed up the concatenations below
542 ddeServer
.reserve(256);
543 ddeTopic
.reserve(256);
544 ddeCommand
.reserve(256);
546 const wxChar
*p
= cmd
.c_str() + 7;
547 while ( *p
&& *p
!= _T('#') )
559 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
562 while ( *p
&& *p
!= _T('#') )
574 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
577 while ( *p
&& *p
!= _T('#') )
589 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
597 // if we want to just launch the program and not wait for its
598 // termination, try to execute DDE command right now, it can succeed if
599 // the process is already running - but as it fails if it's not
600 // running, suppress any errors it might generate
601 if ( !(flags
& wxEXEC_SYNC
) )
604 if ( wxExecuteDDE(ddeServer
, ddeTopic
, ddeCommand
) )
606 // a dummy PID - this is a hack, of course, but it's well worth
607 // it as we don't open a new server each time we're called
608 // which would be quite bad
620 // the IO redirection is only supported with wxUSE_STREAMS
621 BOOL redirect
= FALSE
;
623 #if wxUSE_STREAMS && !defined(__WXWINCE__)
624 wxPipe pipeIn
, pipeOut
, pipeErr
;
626 // we'll save here the copy of pipeIn[Write]
627 HANDLE hpipeStdinWrite
= INVALID_HANDLE_VALUE
;
629 // open the pipes to which child process IO will be redirected if needed
630 if ( handler
&& handler
->IsRedirected() )
632 // create pipes for redirecting stdin, stdout and stderr
633 if ( !pipeIn
.Create() || !pipeOut
.Create() || !pipeErr
.Create() )
635 wxLogSysError(_("Failed to redirect the child process IO"));
637 // indicate failure: we need to return different error code
638 // depending on the sync flag
639 return flags
& wxEXEC_SYNC
? -1 : 0;
644 #endif // wxUSE_STREAMS
646 // create the process
651 #if wxUSE_STREAMS && !defined(__WXWINCE__)
654 si
.dwFlags
= STARTF_USESTDHANDLES
;
656 si
.hStdInput
= pipeIn
[wxPipe::Read
];
657 si
.hStdOutput
= pipeOut
[wxPipe::Write
];
658 si
.hStdError
= pipeErr
[wxPipe::Write
];
660 // when the std IO is redirected, we don't show the (console) process
661 // window by default, but this can be overridden by the caller by
662 // specifying wxEXEC_NOHIDE flag
663 if ( !(flags
& wxEXEC_NOHIDE
) )
665 si
.dwFlags
|= STARTF_USESHOWWINDOW
;
666 si
.wShowWindow
= SW_HIDE
;
669 // we must duplicate the handle to the write side of stdin pipe to make
670 // it non inheritable: indeed, we must close the writing end of pipeIn
671 // before launching the child process as otherwise this handle will be
672 // inherited by the child which will never close it and so the pipe
673 // will never be closed and the child will be left stuck in ReadFile()
674 HANDLE pipeInWrite
= pipeIn
.Detach(wxPipe::Write
);
675 if ( !::DuplicateHandle
677 ::GetCurrentProcess(),
679 ::GetCurrentProcess(),
681 0, // desired access: unused here
682 FALSE
, // not inherited
683 DUPLICATE_SAME_ACCESS
// same access as for src handle
686 wxLogLastError(_T("DuplicateHandle"));
689 ::CloseHandle(pipeInWrite
);
691 #endif // wxUSE_STREAMS
693 PROCESS_INFORMATION pi
;
694 DWORD dwFlags
= CREATE_SUSPENDED
;
696 dwFlags
|= CREATE_DEFAULT_ERROR_MODE
;
699 bool ok
= ::CreateProcess
701 NULL
, // application name (use only cmd line)
703 command
.c_str(), // full command line
704 NULL
, // security attributes: defaults for both
705 NULL
, // the process and its main thread
706 redirect
, // inherit handles if we use pipes
707 dwFlags
, // process creation flags
708 NULL
, // environment (use the same)
709 NULL
, // current directory (use the same)
710 &si
, // startup info (unused here)
714 #if wxUSE_STREAMS && !defined(__WXWINCE__)
715 // we can close the pipe ends used by child anyhow
718 ::CloseHandle(pipeIn
.Detach(wxPipe::Read
));
719 ::CloseHandle(pipeOut
.Detach(wxPipe::Write
));
720 ::CloseHandle(pipeErr
.Detach(wxPipe::Write
));
722 #endif // wxUSE_STREAMS
726 #if wxUSE_STREAMS && !defined(__WXWINCE__)
727 // close the other handles too
730 ::CloseHandle(pipeOut
.Detach(wxPipe::Read
));
731 ::CloseHandle(pipeErr
.Detach(wxPipe::Read
));
733 #endif // wxUSE_STREAMS
735 wxLogSysError(_("Execution of command '%s' failed"), command
.c_str());
737 return flags
& wxEXEC_SYNC
? -1 : 0;
740 #if wxUSE_STREAMS && !defined(__WXWINCE__)
741 // the input buffer bufOut is connected to stdout, this is why it is
742 // called bufOut and not bufIn
743 wxStreamTempInputBuffer bufOut
,
748 // We can now initialize the wxStreams
750 outStream
= new wxPipeInputStream(pipeOut
.Detach(wxPipe::Read
));
752 errStream
= new wxPipeInputStream(pipeErr
.Detach(wxPipe::Read
));
754 inStream
= new wxPipeOutputStream(hpipeStdinWrite
);
756 handler
->SetPipeStreams(outStream
, inStream
, errStream
);
758 bufOut
.Init(outStream
);
759 bufErr
.Init(errStream
);
761 #endif // wxUSE_STREAMS
763 // create a hidden window to receive notification about process
765 HWND hwnd
= wxCreateHiddenWindow
767 &gs_classForHiddenWindow
,
768 wxMSWEXEC_WNDCLASSNAME
,
769 (WNDPROC
)wxExecuteWindowCbk
772 wxASSERT_MSG( hwnd
, wxT("can't create a hidden window for wxExecute") );
775 wxExecuteData
*data
= new wxExecuteData
;
776 data
->hProcess
= pi
.hProcess
;
777 data
->dwProcessId
= pi
.dwProcessId
;
779 data
->state
= (flags
& wxEXEC_SYNC
) != 0;
780 if ( flags
& wxEXEC_SYNC
)
782 // handler may be !NULL for capturing program output, but we don't use
783 // it wxExecuteData struct in this case
784 data
->handler
= NULL
;
788 // may be NULL or not
789 data
->handler
= handler
;
793 HANDLE hThread
= ::CreateThread(NULL
,
800 // resume process we created now - whether the thread creation succeeded or
802 if ( ::ResumeThread(pi
.hThread
) == (DWORD
)-1 )
804 // ignore it - what can we do?
805 wxLogLastError(wxT("ResumeThread in wxExecute"));
808 // close unneeded handle
809 if ( !::CloseHandle(pi
.hThread
) )
810 wxLogLastError(wxT("CloseHandle(hThread)"));
814 wxLogLastError(wxT("CreateThread in wxExecute"));
819 // the process still started up successfully...
820 return pi
.dwProcessId
;
823 ::CloseHandle(hThread
);
825 #if wxUSE_IPC && !defined(__WXWINCE__)
826 // second part of DDE hack: now establish the DDE conversation with the
827 // just launched process
828 if ( !ddeServer
.empty() )
832 // give the process the time to init itself
834 // we use a very big timeout hoping that WaitForInputIdle() will return
835 // much sooner, but not INFINITE just in case the process hangs
836 // completely - like this we will regain control sooner or later
837 switch ( ::WaitForInputIdle(pi
.hProcess
, 10000 /* 10 seconds */) )
840 wxFAIL_MSG( _T("unexpected WaitForInputIdle() return code") );
844 wxLogLastError(_T("WaitForInputIdle() in wxExecute"));
847 wxLogDebug(_T("Timeout too small in WaitForInputIdle"));
853 // ok, process ready to accept DDE requests
854 ok
= wxExecuteDDE(ddeServer
, ddeTopic
, ddeCommand
);
859 wxLogDebug(_T("Failed to send DDE request to the process \"%s\"."),
865 if ( !(flags
& wxEXEC_SYNC
) )
867 // clean up will be done when the process terminates
870 return pi
.dwProcessId
;
873 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
874 wxCHECK_MSG( traits
, -1, _T("no wxAppTraits in wxExecute()?") );
876 // disable all app windows while waiting for the child process to finish
877 void *cookie
= traits
->BeforeChildWaitLoop();
879 // wait until the child process terminates
880 while ( data
->state
)
882 #if wxUSE_STREAMS && !defined(__WXWINCE__)
885 #endif // wxUSE_STREAMS
887 // don't eat 100% of the CPU -- ugly but anything else requires
888 // real async IO which we don't have for the moment
891 // we must process messages or we'd never get wxWM_PROC_TERMINATED
892 traits
->AlwaysYield();
895 traits
->AfterChildWaitLoop(cookie
);
897 DWORD dwExitCode
= data
->dwExitCode
;
900 // return the exit code
904 long wxExecute(wxChar
**argv
, int flags
, wxProcess
*handler
)
917 return wxExecute(command
, flags
, handler
);