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"
39 #include "wx/stream.h"
40 #include "wx/process.h"
43 #include "wx/apptrait.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(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
75 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
82 #include "wx/dde.h" // for WX_DDE hack in wxExecute
85 // ----------------------------------------------------------------------------
87 // ----------------------------------------------------------------------------
89 // this message is sent when the process we're waiting for terminates
90 #define wxWM_PROC_TERMINATED (WM_USER + 10000)
92 // ----------------------------------------------------------------------------
93 // this module globals
94 // ----------------------------------------------------------------------------
96 // we need to create a hidden window to receive the process termination
97 // notifications and for this we need a (Win) class name for it which we will
98 // register the first time it's needed
99 static const wxChar
*gs_classForHiddenWindow
= NULL
;
101 // ----------------------------------------------------------------------------
103 // ----------------------------------------------------------------------------
105 // structure describing the process we're being waiting for
112 if ( !::CloseHandle(hProcess
) )
114 wxLogLastError(wxT("CloseHandle(hProcess)"));
119 HWND hWnd
; // window to send wxWM_PROC_TERMINATED to
120 HANDLE hProcess
; // handle of the process
121 DWORD dwProcessId
; // pid of the process
123 DWORD dwExitCode
; // the exit code of the process
124 bool state
; // set to FALSE when the process finishes
127 #if defined(__WIN32__) && wxUSE_STREAMS && !defined(__WXWINCE__)
129 // ----------------------------------------------------------------------------
131 // ----------------------------------------------------------------------------
133 class wxPipeInputStream
: public wxInputStream
136 wxPipeInputStream(HANDLE hInput
);
137 virtual ~wxPipeInputStream();
139 // returns TRUE if the pipe is still opened
140 bool IsOpened() const { return m_hInput
!= INVALID_HANDLE_VALUE
; }
142 // returns TRUE if there is any data to be read from the pipe
143 virtual bool CanRead() const;
146 size_t OnSysRead(void *buffer
, size_t len
);
151 DECLARE_NO_COPY_CLASS(wxPipeInputStream
)
154 class wxPipeOutputStream
: public wxOutputStream
157 wxPipeOutputStream(HANDLE hOutput
);
158 virtual ~wxPipeOutputStream();
161 size_t OnSysWrite(const void *buffer
, size_t len
);
166 DECLARE_NO_COPY_CLASS(wxPipeOutputStream
)
169 // define this to let wxexec.cpp know that we know what we're doing
170 #define _WX_USED_BY_WXEXECUTE_
171 #include "../common/execcmn.cpp"
173 // ----------------------------------------------------------------------------
174 // wxPipe represents a Win32 anonymous pipe
175 // ----------------------------------------------------------------------------
180 // the symbolic names for the pipe ends
187 // default ctor doesn't do anything
188 wxPipe() { m_handles
[Read
] = m_handles
[Write
] = INVALID_HANDLE_VALUE
; }
190 // create the pipe, return TRUE if ok, FALSE on error
193 // default secutiry attributes
194 SECURITY_ATTRIBUTES security
;
196 security
.nLength
= sizeof(security
);
197 security
.lpSecurityDescriptor
= NULL
;
198 security
.bInheritHandle
= TRUE
; // to pass it to the child
200 if ( !::CreatePipe(&m_handles
[0], &m_handles
[1], &security
, 0) )
202 wxLogSysError(_("Failed to create an anonymous pipe"));
210 // return TRUE if we were created successfully
211 bool IsOk() const { return m_handles
[Read
] != INVALID_HANDLE_VALUE
; }
213 // return the descriptor for one of the pipe ends
214 HANDLE
operator[](Direction which
) const
216 wxASSERT_MSG( which
>= 0 && (size_t)which
< WXSIZEOF(m_handles
),
217 _T("invalid pipe index") );
219 return m_handles
[which
];
222 // detach a descriptor, meaning that the pipe dtor won't close it, and
224 HANDLE
Detach(Direction which
)
226 wxASSERT_MSG( which
>= 0 && (size_t)which
< WXSIZEOF(m_handles
),
227 _T("invalid pipe index") );
229 HANDLE handle
= m_handles
[which
];
230 m_handles
[which
] = INVALID_HANDLE_VALUE
;
235 // close the pipe descriptors
238 for ( size_t n
= 0; n
< WXSIZEOF(m_handles
); n
++ )
240 if ( m_handles
[n
] != INVALID_HANDLE_VALUE
)
242 ::CloseHandle(m_handles
[n
]);
243 m_handles
[n
] = INVALID_HANDLE_VALUE
;
248 // dtor closes the pipe descriptors
249 ~wxPipe() { Close(); }
255 #endif // wxUSE_STREAMS
257 // ============================================================================
259 // ============================================================================
263 // ----------------------------------------------------------------------------
264 // process termination detecting support
265 // ----------------------------------------------------------------------------
267 // thread function for the thread monitoring the process termination
268 static DWORD __stdcall
wxExecuteThread(void *arg
)
270 wxExecuteData
* const data
= (wxExecuteData
*)arg
;
272 if ( ::WaitForSingleObject(data
->hProcess
, INFINITE
) != WAIT_OBJECT_0
)
274 wxLogDebug(_T("Waiting for the process termination failed!"));
278 if ( !::GetExitCodeProcess(data
->hProcess
, &data
->dwExitCode
) )
280 wxLogLastError(wxT("GetExitCodeProcess"));
283 wxASSERT_MSG( data
->dwExitCode
!= STILL_ACTIVE
,
284 wxT("process should have terminated") );
286 // send a message indicating process termination to the window
287 ::SendMessage(data
->hWnd
, wxWM_PROC_TERMINATED
, 0, (LPARAM
)data
);
292 // window procedure of a hidden window which is created just to receive
293 // the notification message when a process exits
294 LRESULT APIENTRY _EXPORT
wxExecuteWindowCbk(HWND hWnd
, UINT message
,
295 WPARAM wParam
, LPARAM lParam
)
297 if ( message
== wxWM_PROC_TERMINATED
)
299 DestroyWindow(hWnd
); // we don't need it any more
301 wxExecuteData
* const data
= (wxExecuteData
*)lParam
;
304 data
->handler
->OnTerminate((int)data
->dwProcessId
,
305 (int)data
->dwExitCode
);
310 // we're executing synchronously, tell the waiting thread
311 // that the process finished
316 // asynchronous execution - we should do the clean up
324 return ::DefWindowProc(hWnd
, message
, wParam
, lParam
);
328 // ============================================================================
329 // implementation of IO redirection support classes
330 // ============================================================================
332 #if wxUSE_STREAMS && !defined(__WXWINCE__)
334 // ----------------------------------------------------------------------------
335 // wxPipeInputStreams
336 // ----------------------------------------------------------------------------
338 wxPipeInputStream::wxPipeInputStream(HANDLE hInput
)
343 wxPipeInputStream::~wxPipeInputStream()
345 if ( m_hInput
!= INVALID_HANDLE_VALUE
)
346 ::CloseHandle(m_hInput
);
349 bool wxPipeInputStream::CanRead() const
356 // function name is misleading, it works with anon pipes as well
357 DWORD rc
= ::PeekNamedPipe
360 NULL
, 0, // ptr to buffer and its size
361 NULL
, // [out] bytes read
362 &nAvailable
, // [out] bytes available
363 NULL
// [out] bytes left
368 if ( ::GetLastError() != ERROR_BROKEN_PIPE
)
371 wxLogLastError(_T("PeekNamedPipe"));
374 // don't try to continue reading from a pipe if an error occured or if
375 // it had been closed
376 ::CloseHandle(m_hInput
);
378 wxPipeInputStream
*self
= wxConstCast(this, wxPipeInputStream
);
380 self
->m_hInput
= INVALID_HANDLE_VALUE
;
381 self
->m_lasterror
= wxSTREAM_EOF
;
386 return nAvailable
!= 0;
389 size_t wxPipeInputStream::OnSysRead(void *buffer
, size_t len
)
393 m_lasterror
= wxSTREAM_EOF
;
399 if ( !::ReadFile(m_hInput
, buffer
, len
, &bytesRead
, NULL
) )
401 m_lasterror
= ::GetLastError() == ERROR_BROKEN_PIPE
403 : wxSTREAM_READ_ERROR
;
406 // bytesRead is set to 0, as desired, if an error occured
410 // ----------------------------------------------------------------------------
411 // wxPipeOutputStream
412 // ----------------------------------------------------------------------------
414 wxPipeOutputStream::wxPipeOutputStream(HANDLE hOutput
)
419 wxPipeOutputStream::~wxPipeOutputStream()
421 ::CloseHandle(m_hOutput
);
424 size_t wxPipeOutputStream::OnSysWrite(const void *buffer
, size_t len
)
428 m_lasterror
= wxSTREAM_NO_ERROR
;
429 if ( !::WriteFile(m_hOutput
, buffer
, len
, &bytesWritten
, NULL
) )
431 m_lasterror
= ::GetLastError() == ERROR_BROKEN_PIPE
433 : wxSTREAM_WRITE_ERROR
;
439 #endif // wxUSE_STREAMS
443 // ============================================================================
444 // wxExecute functions family
445 // ============================================================================
449 // connect to the given server via DDE and ask it to execute the command
450 static bool wxExecuteDDE(const wxString
& ddeServer
,
451 const wxString
& ddeTopic
,
452 const wxString
& ddeCommand
)
457 wxConnectionBase
*conn
= client
.MakeConnection(wxEmptyString
,
464 else // connected to DDE server
466 // the added complication here is that although most programs use
467 // XTYP_EXECUTE for their DDE API, some important ones -- like Word
468 // and other MS stuff - use XTYP_REQUEST!
470 // moreover, anotheri mportant program (IE) understands both but
471 // returns an error from Execute() so we must try Request() first
472 // to avoid doing it twice
474 // we're prepared for this one to fail, so don't show errors
477 ok
= conn
->Request(ddeCommand
) != NULL
;
482 // now try execute -- but show the errors
483 ok
= conn
->Execute(ddeCommand
);
492 long wxExecute(const wxString
& cmd
, int flags
, wxProcess
*handler
)
494 wxCHECK_MSG( !!cmd
, 0, wxT("empty command in wxExecute") );
497 // for many reasons, the code below breaks down if it's called from another
498 // thread -- this could be fixed, but as Unix versions don't support this
499 // neither I don't want to waste time on this now
500 wxASSERT_MSG( wxThread::IsMain(),
501 _T("wxExecute() can be called only from the main thread") );
502 #endif // wxUSE_THREADS
507 // DDE hack: this is really not pretty, but we need to allow this for
508 // transparent handling of DDE servers in wxMimeTypesManager. Usually it
509 // returns the command which should be run to view/open/... a file of the
510 // given type. Sometimes, however, this command just launches the server
511 // and an additional DDE request must be made to really open the file. To
512 // keep all this well hidden from the application, we allow a special form
513 // of command: WX_DDE#<command>#DDE_SERVER#DDE_TOPIC#DDE_COMMAND in which
514 // case we execute just <command> and process the rest below
515 wxString ddeServer
, ddeTopic
, ddeCommand
;
516 static const size_t lenDdePrefix
= 7; // strlen("WX_DDE:")
517 if ( cmd
.Left(lenDdePrefix
) == _T("WX_DDE#") )
519 // speed up the concatenations below
520 ddeServer
.reserve(256);
521 ddeTopic
.reserve(256);
522 ddeCommand
.reserve(256);
524 const wxChar
*p
= cmd
.c_str() + 7;
525 while ( *p
&& *p
!= _T('#') )
537 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
540 while ( *p
&& *p
!= _T('#') )
552 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
555 while ( *p
&& *p
!= _T('#') )
567 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
575 // if we want to just launch the program and not wait for its
576 // termination, try to execute DDE command right now, it can succeed if
577 // the process is already running - but as it fails if it's not
578 // running, suppress any errors it might generate
579 if ( !(flags
& wxEXEC_SYNC
) )
582 if ( wxExecuteDDE(ddeServer
, ddeTopic
, ddeCommand
) )
584 // a dummy PID - this is a hack, of course, but it's well worth
585 // it as we don't open a new server each time we're called
586 // which would be quite bad
598 // the IO redirection is only supported with wxUSE_STREAMS
599 BOOL redirect
= FALSE
;
601 #if wxUSE_STREAMS && !defined(__WXWINCE__)
602 wxPipe pipeIn
, pipeOut
, pipeErr
;
604 // we'll save here the copy of pipeIn[Write]
605 HANDLE hpipeStdinWrite
= INVALID_HANDLE_VALUE
;
607 // open the pipes to which child process IO will be redirected if needed
608 if ( handler
&& handler
->IsRedirected() )
610 // create pipes for redirecting stdin, stdout and stderr
611 if ( !pipeIn
.Create() || !pipeOut
.Create() || !pipeErr
.Create() )
613 wxLogSysError(_("Failed to redirect the child process IO"));
615 // indicate failure: we need to return different error code
616 // depending on the sync flag
617 return flags
& wxEXEC_SYNC
? -1 : 0;
622 #endif // wxUSE_STREAMS
624 // create the process
629 #if wxUSE_STREAMS && !defined(__WXWINCE__)
632 si
.dwFlags
= STARTF_USESTDHANDLES
;
634 si
.hStdInput
= pipeIn
[wxPipe::Read
];
635 si
.hStdOutput
= pipeOut
[wxPipe::Write
];
636 si
.hStdError
= pipeErr
[wxPipe::Write
];
638 // when the std IO is redirected, we don't show the (console) process
639 // window by default, but this can be overridden by the caller by
640 // specifying wxEXEC_NOHIDE flag
641 if ( !(flags
& wxEXEC_NOHIDE
) )
643 si
.dwFlags
|= STARTF_USESHOWWINDOW
;
644 si
.wShowWindow
= SW_HIDE
;
647 // we must duplicate the handle to the write side of stdin pipe to make
648 // it non inheritable: indeed, we must close the writing end of pipeIn
649 // before launching the child process as otherwise this handle will be
650 // inherited by the child which will never close it and so the pipe
651 // will never be closed and the child will be left stuck in ReadFile()
652 HANDLE pipeInWrite
= pipeIn
.Detach(wxPipe::Write
);
653 if ( !::DuplicateHandle
655 ::GetCurrentProcess(),
657 ::GetCurrentProcess(),
659 0, // desired access: unused here
660 FALSE
, // not inherited
661 DUPLICATE_SAME_ACCESS
// same access as for src handle
664 wxLogLastError(_T("DuplicateHandle"));
667 ::CloseHandle(pipeInWrite
);
669 #endif // wxUSE_STREAMS
671 PROCESS_INFORMATION pi
;
672 DWORD dwFlags
= CREATE_SUSPENDED
;
674 dwFlags
|= CREATE_DEFAULT_ERROR_MODE
;
677 bool ok
= ::CreateProcess
679 NULL
, // application name (use only cmd line)
681 command
.c_str(), // full command line
682 NULL
, // security attributes: defaults for both
683 NULL
, // the process and its main thread
684 redirect
, // inherit handles if we use pipes
685 dwFlags
, // process creation flags
686 NULL
, // environment (use the same)
687 NULL
, // current directory (use the same)
688 &si
, // startup info (unused here)
692 #if wxUSE_STREAMS && !defined(__WXWINCE__)
693 // we can close the pipe ends used by child anyhow
696 ::CloseHandle(pipeIn
.Detach(wxPipe::Read
));
697 ::CloseHandle(pipeOut
.Detach(wxPipe::Write
));
698 ::CloseHandle(pipeErr
.Detach(wxPipe::Write
));
700 #endif // wxUSE_STREAMS
704 #if wxUSE_STREAMS && !defined(__WXWINCE__)
705 // close the other handles too
708 ::CloseHandle(pipeOut
.Detach(wxPipe::Read
));
709 ::CloseHandle(pipeErr
.Detach(wxPipe::Read
));
711 #endif // wxUSE_STREAMS
713 wxLogSysError(_("Execution of command '%s' failed"), command
.c_str());
715 return flags
& wxEXEC_SYNC
? -1 : 0;
718 #if wxUSE_STREAMS && !defined(__WXWINCE__)
719 // the input buffer bufOut is connected to stdout, this is why it is
720 // called bufOut and not bufIn
721 wxStreamTempInputBuffer bufOut
,
726 // We can now initialize the wxStreams
728 outStream
= new wxPipeInputStream(pipeOut
.Detach(wxPipe::Read
));
730 errStream
= new wxPipeInputStream(pipeErr
.Detach(wxPipe::Read
));
732 inStream
= new wxPipeOutputStream(hpipeStdinWrite
);
734 handler
->SetPipeStreams(outStream
, inStream
, errStream
);
736 bufOut
.Init(outStream
);
737 bufErr
.Init(errStream
);
739 #endif // wxUSE_STREAMS
741 // register the class for the hidden window used for the notifications
742 if ( !gs_classForHiddenWindow
)
744 gs_classForHiddenWindow
= _T("wxHiddenWindow");
747 wxZeroMemory(wndclass
);
748 wndclass
.lpfnWndProc
= (WNDPROC
)wxExecuteWindowCbk
;
749 wndclass
.hInstance
= wxGetInstance();
750 wndclass
.lpszClassName
= gs_classForHiddenWindow
;
752 if ( !::RegisterClass(&wndclass
) )
754 wxLogLastError(wxT("RegisterClass(hidden window)"));
758 // create a hidden window to receive notification about process
761 HWND hwnd
= ::CreateWindow(gs_classForHiddenWindow
, NULL
,
764 (HMENU
)NULL
, wxGetInstance(), 0);
766 HWND hwnd
= ::CreateWindow(gs_classForHiddenWindow
, NULL
,
769 (HMENU
)NULL
, wxGetInstance(), 0);
771 wxASSERT_MSG( hwnd
, wxT("can't create a hidden window for wxExecute") );
774 wxExecuteData
*data
= new wxExecuteData
;
775 data
->hProcess
= pi
.hProcess
;
776 data
->dwProcessId
= pi
.dwProcessId
;
778 data
->state
= (flags
& wxEXEC_SYNC
) != 0;
779 if ( flags
& wxEXEC_SYNC
)
781 // handler may be !NULL for capturing program output, but we don't use
782 // it wxExecuteData struct in this case
783 data
->handler
= NULL
;
787 // may be NULL or not
788 data
->handler
= handler
;
792 HANDLE hThread
= ::CreateThread(NULL
,
799 // resume process we created now - whether the thread creation succeeded or
801 if ( ::ResumeThread(pi
.hThread
) == (DWORD
)-1 )
803 // ignore it - what can we do?
804 wxLogLastError(wxT("ResumeThread in wxExecute"));
807 // close unneeded handle
808 if ( !::CloseHandle(pi
.hThread
) )
809 wxLogLastError(wxT("CloseHandle(hThread)"));
813 wxLogLastError(wxT("CreateThread in wxExecute"));
818 // the process still started up successfully...
819 return pi
.dwProcessId
;
822 ::CloseHandle(hThread
);
824 #if wxUSE_IPC && !defined(__WXWINCE__)
825 // second part of DDE hack: now establish the DDE conversation with the
826 // just launched process
827 if ( !ddeServer
.empty() )
831 // give the process the time to init itself
833 // we use a very big timeout hoping that WaitForInputIdle() will return
834 // much sooner, but not INFINITE just in case the process hangs
835 // completely - like this we will regain control sooner or later
836 switch ( ::WaitForInputIdle(pi
.hProcess
, 10000 /* 10 seconds */) )
839 wxFAIL_MSG( _T("unexpected WaitForInputIdle() return code") );
843 wxLogLastError(_T("WaitForInputIdle() in wxExecute"));
846 wxLogDebug(_T("Timeout too small in WaitForInputIdle"));
852 // ok, process ready to accept DDE requests
853 ok
= wxExecuteDDE(ddeServer
, ddeTopic
, ddeCommand
);
858 wxLogDebug(_T("Failed to send DDE request to the process \"%s\"."),
864 if ( !(flags
& wxEXEC_SYNC
) )
866 // clean up will be done when the process terminates
869 return pi
.dwProcessId
;
872 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
873 wxCHECK_MSG( traits
, -1, _T("no wxAppTraits in wxExecute()?") );
875 // disable all app windows while waiting for the child process to finish
876 void *cookie
= traits
->BeforeChildWaitLoop();
878 // wait until the child process terminates
879 while ( data
->state
)
881 #if wxUSE_STREAMS && !defined(__WXWINCE__)
884 #endif // wxUSE_STREAMS
886 // don't eat 100% of the CPU -- ugly but anything else requires
887 // real async IO which we don't have for the moment
890 // we must process messages or we'd never get wxWM_PROC_TERMINATED
891 traits
->AlwaysYield();
894 traits
->AfterChildWaitLoop(cookie
);
896 DWORD dwExitCode
= data
->dwExitCode
;
899 // return the exit code
903 long wxExecute(wxChar
**argv
, int flags
, wxProcess
*handler
)
916 return wxExecute(command
, flags
, handler
);