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"
40 #include "wx/stream.h"
41 #include "wx/process.h"
44 #include "wx/msw/private.h"
48 #if !defined(__GNUWIN32__) && !defined(__WXWINE__) && !defined(__SALFORDC__) && !defined(__WXMICROWIN__)
55 #if defined(__GNUWIN32__) && !defined(__TWIN32__)
56 #include <sys/unistd.h>
60 #if defined(__WIN32__) && !defined(__WXWINE__) && !defined(__WXMICROWIN__)
72 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
79 #include "wx/dde.h" // for WX_DDE hack in wxExecute
82 // ----------------------------------------------------------------------------
84 // ----------------------------------------------------------------------------
86 // this message is sent when the process we're waiting for terminates
87 #define wxWM_PROC_TERMINATED (WM_USER + 10000)
89 // ----------------------------------------------------------------------------
90 // this module globals
91 // ----------------------------------------------------------------------------
93 // we need to create a hidden window to receive the process termination
94 // notifications and for this we need a (Win) class name for it which we will
95 // register the first time it's needed
96 static const wxChar
*gs_classForHiddenWindow
= NULL
;
98 // ----------------------------------------------------------------------------
100 // ----------------------------------------------------------------------------
102 // structure describing the process we're being waiting for
109 if ( !::CloseHandle(hProcess
) )
111 wxLogLastError(wxT("CloseHandle(hProcess)"));
116 HWND hWnd
; // window to send wxWM_PROC_TERMINATED to
117 HANDLE hProcess
; // handle of the process
118 DWORD dwProcessId
; // pid of the process
120 DWORD dwExitCode
; // the exit code of the process
121 bool state
; // set to FALSE when the process finishes
124 #if defined(__WIN32__) && wxUSE_STREAMS
126 // ----------------------------------------------------------------------------
128 // ----------------------------------------------------------------------------
130 class wxPipeInputStream
: public wxInputStream
133 wxPipeInputStream(HANDLE hInput
);
134 virtual ~wxPipeInputStream();
136 // returns TRUE if the pipe is still opened
137 bool IsOpened() const { return m_hInput
!= INVALID_HANDLE_VALUE
; }
139 // returns TRUE if there is any data to be read from the pipe
140 bool IsAvailable() const;
143 size_t OnSysRead(void *buffer
, size_t len
);
149 class wxPipeOutputStream
: public wxOutputStream
152 wxPipeOutputStream(HANDLE hOutput
);
153 virtual ~wxPipeOutputStream();
156 size_t OnSysWrite(const void *buffer
, size_t len
);
162 // define this to let wxexec.cpp know that we know what we're doing
163 #define _WX_USED_BY_WXEXECUTE_
164 #include "../common/execcmn.cpp"
166 // ----------------------------------------------------------------------------
167 // wxPipe represents a Win32 anonymous pipe
168 // ----------------------------------------------------------------------------
173 // the symbolic names for the pipe ends
180 // default ctor doesn't do anything
181 wxPipe() { m_handles
[Read
] = m_handles
[Write
] = INVALID_HANDLE_VALUE
; }
183 // create the pipe, return TRUE if ok, FALSE on error
186 // default secutiry attributes
187 SECURITY_ATTRIBUTES security
;
189 security
.nLength
= sizeof(security
);
190 security
.lpSecurityDescriptor
= NULL
;
191 security
.bInheritHandle
= TRUE
; // to pass it to the child
193 if ( !::CreatePipe(&m_handles
[0], &m_handles
[1], &security
, 0) )
195 wxLogSysError(_("Failed to create an anonymous pipe"));
203 // return TRUE if we were created successfully
204 bool IsOk() const { return m_handles
[Read
] != INVALID_HANDLE_VALUE
; }
206 // return the descriptor for one of the pipe ends
207 HANDLE
operator[](Direction which
) const
209 wxASSERT_MSG( which
>= 0 && (size_t)which
< WXSIZEOF(m_handles
),
210 _T("invalid pipe index") );
212 return m_handles
[which
];
215 // detach a descriptor, meaning that the pipe dtor won't close it, and
217 HANDLE
Detach(Direction which
)
219 wxASSERT_MSG( which
>= 0 && (size_t)which
< WXSIZEOF(m_handles
),
220 _T("invalid pipe index") );
222 HANDLE handle
= m_handles
[which
];
223 m_handles
[which
] = INVALID_HANDLE_VALUE
;
228 // close the pipe descriptors
231 for ( size_t n
= 0; n
< WXSIZEOF(m_handles
); n
++ )
233 if ( m_handles
[n
] != INVALID_HANDLE_VALUE
)
235 ::CloseHandle(m_handles
[n
]);
236 m_handles
[n
] = INVALID_HANDLE_VALUE
;
241 // dtor closes the pipe descriptors
242 ~wxPipe() { Close(); }
248 #endif // wxUSE_STREAMS
250 // ============================================================================
252 // ============================================================================
256 // ----------------------------------------------------------------------------
257 // process termination detecting support
258 // ----------------------------------------------------------------------------
260 // thread function for the thread monitoring the process termination
261 static DWORD __stdcall
wxExecuteThread(void *arg
)
263 wxExecuteData
*data
= (wxExecuteData
*)arg
;
265 if ( ::WaitForSingleObject(data
->hProcess
, INFINITE
) != WAIT_OBJECT_0
)
267 wxLogDebug(_T("Waiting for the process termination failed!"));
271 if ( !::GetExitCodeProcess(data
->hProcess
, &data
->dwExitCode
) )
273 wxLogLastError(wxT("GetExitCodeProcess"));
276 wxASSERT_MSG( data
->dwExitCode
!= STILL_ACTIVE
,
277 wxT("process should have terminated") );
279 // send a message indicating process termination to the window
280 ::SendMessage(data
->hWnd
, wxWM_PROC_TERMINATED
, 0, (LPARAM
)data
);
285 // window procedure of a hidden window which is created just to receive
286 // the notification message when a process exits
287 LRESULT APIENTRY _EXPORT
wxExecuteWindowCbk(HWND hWnd
, UINT message
,
288 WPARAM wParam
, LPARAM lParam
)
290 if ( message
== wxWM_PROC_TERMINATED
)
292 DestroyWindow(hWnd
); // we don't need it any more
294 wxExecuteData
*data
= (wxExecuteData
*)lParam
;
297 data
->handler
->OnTerminate((int)data
->dwProcessId
,
298 (int)data
->dwExitCode
);
303 // we're executing synchronously, tell the waiting thread
304 // that the process finished
309 // asynchronous execution - we should do the clean up
317 return DefWindowProc(hWnd
, message
, wParam
, lParam
);
321 // ============================================================================
322 // implementation of IO redirection support classes
323 // ============================================================================
327 // ----------------------------------------------------------------------------
328 // wxPipeInputStreams
329 // ----------------------------------------------------------------------------
331 wxPipeInputStream::wxPipeInputStream(HANDLE hInput
)
336 wxPipeInputStream::~wxPipeInputStream()
338 if ( m_hInput
!= INVALID_HANDLE_VALUE
)
339 ::CloseHandle(m_hInput
);
342 bool wxPipeInputStream::IsAvailable() const
349 // function name is misleading, it works with anon pipes as well
350 DWORD rc
= ::PeekNamedPipe
353 NULL
, 0, // ptr to buffer and its size
354 NULL
, // [out] bytes read
355 &nAvailable
, // [out] bytes available
356 NULL
// [out] bytes left
361 if ( ::GetLastError() != ERROR_BROKEN_PIPE
)
364 wxLogLastError(_T("PeekNamedPipe"));
367 // don't try to continue reading from a pipe if an error occured or if
368 // it had been closed
369 ::CloseHandle(m_hInput
);
371 wxConstCast(this, wxPipeInputStream
)->m_hInput
= INVALID_HANDLE_VALUE
;
376 return nAvailable
!= 0;
379 size_t wxPipeInputStream::OnSysRead(void *buffer
, size_t len
)
381 // reading from a pipe may block if there is no more data, always check for
383 if ( !IsAvailable() )
385 m_lasterror
= wxSTREAM_EOF
;
390 m_lasterror
= wxSTREAM_NOERROR
;
393 if ( !::ReadFile(m_hInput
, buffer
, len
, &bytesRead
, NULL
) )
395 if ( ::GetLastError() == ERROR_BROKEN_PIPE
)
396 m_lasterror
= wxSTREAM_EOF
;
398 m_lasterror
= wxSTREAM_READ_ERROR
;
404 // ----------------------------------------------------------------------------
405 // wxPipeOutputStream
406 // ----------------------------------------------------------------------------
408 wxPipeOutputStream::wxPipeOutputStream(HANDLE hOutput
)
413 wxPipeOutputStream::~wxPipeOutputStream()
415 ::CloseHandle(m_hOutput
);
418 size_t wxPipeOutputStream::OnSysWrite(const void *buffer
, size_t len
)
422 m_lasterror
= wxSTREAM_NOERROR
;
423 if ( !::WriteFile(m_hOutput
, buffer
, len
, &bytesRead
, NULL
) )
425 if ( ::GetLastError() == ERROR_BROKEN_PIPE
)
426 m_lasterror
= wxSTREAM_EOF
;
428 m_lasterror
= wxSTREAM_READ_ERROR
;
434 #endif // wxUSE_STREAMS
438 // ============================================================================
439 // wxExecute functions family
440 // ============================================================================
444 // connect to the given server via DDE and ask it to execute the command
445 static bool wxExecuteDDE(const wxString
& ddeServer
,
446 const wxString
& ddeTopic
,
447 const wxString
& ddeCommand
)
452 wxConnectionBase
*conn
= client
.MakeConnection(_T(""),
459 else // connected to DDE server
461 // the added complication here is that although most
462 // programs use XTYP_EXECUTE for their DDE API, some
463 // important ones - like IE and other MS stuff - use
466 // so we try it first and then the other one if it
470 ok
= conn
->Request(ddeCommand
) != NULL
;
475 // now try execute - but show the errors
476 ok
= conn
->Execute(ddeCommand
);
485 long wxExecute(const wxString
& cmd
, int flags
, wxProcess
*handler
)
487 wxCHECK_MSG( !!cmd
, 0, wxT("empty command in wxExecute") );
492 // DDE hack: this is really not pretty, but we need to allow this for
493 // transparent handling of DDE servers in wxMimeTypesManager. Usually it
494 // returns the command which should be run to view/open/... a file of the
495 // given type. Sometimes, however, this command just launches the server
496 // and an additional DDE request must be made to really open the file. To
497 // keep all this well hidden from the application, we allow a special form
498 // of command: WX_DDE#<command>#DDE_SERVER#DDE_TOPIC#DDE_COMMAND in which
499 // case we execute just <command> and process the rest below
500 wxString ddeServer
, ddeTopic
, ddeCommand
;
501 static const size_t lenDdePrefix
= 7; // strlen("WX_DDE:")
502 if ( cmd
.Left(lenDdePrefix
) == _T("WX_DDE#") )
504 // speed up the concatenations below
505 ddeServer
.reserve(256);
506 ddeTopic
.reserve(256);
507 ddeCommand
.reserve(256);
509 const wxChar
*p
= cmd
.c_str() + 7;
510 while ( *p
&& *p
!= _T('#') )
522 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
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"));
560 // if we want to just launch the program and not wait for its
561 // termination, try to execute DDE command right now, it can succeed if
562 // the process is already running - but as it fails if it's not
563 // running, suppress any errors it might generate
564 if ( !(flags
& wxEXEC_SYNC
) )
567 if ( wxExecuteDDE(ddeServer
, ddeTopic
, ddeCommand
) )
569 // a dummy PID - this is a hack, of course, but it's well worth
570 // it as we don't open a new server each time we're called
571 // which would be quite bad
583 #if defined(__WIN32__) && !defined(__TWIN32__)
585 // the IO redirection is only supported with wxUSE_STREAMS
586 BOOL redirect
= FALSE
;
589 wxPipe pipeIn
, pipeOut
, pipeErr
;
591 // we'll save here the copy of pipeIn[Write]
592 HANDLE hpipeStdinWrite
= INVALID_HANDLE_VALUE
;
594 // open the pipes to which child process IO will be redirected if needed
595 if ( handler
&& handler
->IsRedirected() )
597 // create pipes for redirecting stdin, stdout and stderr
598 if ( !pipeIn
.Create() || !pipeOut
.Create() || !pipeErr
.Create() )
600 wxLogSysError(_("Failed to redirect the child process IO"));
602 // indicate failure: we need to return different error code
603 // depending on the sync flag
604 return flags
& wxEXEC_SYNC
? -1 : 0;
609 #endif // wxUSE_STREAMS
611 // create the process
619 si
.dwFlags
= STARTF_USESTDHANDLES
;
621 si
.hStdInput
= pipeIn
[wxPipe::Read
];
622 si
.hStdOutput
= pipeOut
[wxPipe::Write
];
623 si
.hStdError
= pipeErr
[wxPipe::Write
];
625 // when the std IO is redirected, we don't show the (console) process
626 // window by default, but this can be overridden by the caller by
627 // specifying wxEXEC_NOHIDE flag
628 if ( !(flags
& wxEXEC_NOHIDE
) )
630 si
.dwFlags
|= STARTF_USESHOWWINDOW
;
631 si
.wShowWindow
= SW_HIDE
;
634 // we must duplicate the handle to the write side of stdin pipe to make
635 // it non inheritable: indeed, we must close the writing end of pipeIn
636 // before launching the child process as otherwise this handle will be
637 // inherited by the child which will never close it and so the pipe
638 // will never be closed and the child will be left stuck in ReadFile()
639 HANDLE pipeInWrite
= pipeIn
.Detach(wxPipe::Write
);
640 if ( !::DuplicateHandle
642 ::GetCurrentProcess(),
644 ::GetCurrentProcess(),
646 0, // desired access: unused here
647 FALSE
, // not inherited
648 DUPLICATE_SAME_ACCESS
// same access as for src handle
651 wxLogLastError(_T("DuplicateHandle"));
654 ::CloseHandle(pipeInWrite
);
656 #endif // wxUSE_STREAMS
658 PROCESS_INFORMATION pi
;
659 DWORD dwFlags
= CREATE_DEFAULT_ERROR_MODE
| CREATE_SUSPENDED
;
661 bool ok
= ::CreateProcess
663 NULL
, // application name (use only cmd line)
665 command
.c_str(), // full command line
666 NULL
, // security attributes: defaults for both
667 NULL
, // the process and its main thread
668 redirect
, // inherit handles if we use pipes
669 dwFlags
, // process creation flags
670 NULL
, // environment (use the same)
671 NULL
, // current directory (use the same)
672 &si
, // startup info (unused here)
677 // we can close the pipe ends used by child anyhow
680 ::CloseHandle(pipeIn
.Detach(wxPipe::Read
));
681 ::CloseHandle(pipeOut
.Detach(wxPipe::Write
));
682 ::CloseHandle(pipeErr
.Detach(wxPipe::Write
));
684 #endif // wxUSE_STREAMS
689 // close the other handles too
692 ::CloseHandle(pipeOut
.Detach(wxPipe::Read
));
693 ::CloseHandle(pipeErr
.Detach(wxPipe::Read
));
695 #endif // wxUSE_STREAMS
697 wxLogSysError(_("Execution of command '%s' failed"), command
.c_str());
699 return flags
& wxEXEC_SYNC
? -1 : 0;
703 // the input buffer bufOut is connected to stdout, this is why it is
704 // called bufOut and not bufIn
705 wxStreamTempInputBuffer bufOut
,
710 // We can now initialize the wxStreams
712 outStream
= new wxPipeInputStream(pipeOut
.Detach(wxPipe::Read
));
714 errStream
= new wxPipeInputStream(pipeErr
.Detach(wxPipe::Read
));
716 inStream
= new wxPipeOutputStream(hpipeStdinWrite
);
718 handler
->SetPipeStreams(outStream
, inStream
, errStream
);
720 bufOut
.Init(outStream
);
721 bufErr
.Init(errStream
);
723 #endif // wxUSE_STREAMS
725 // register the class for the hidden window used for the notifications
726 if ( !gs_classForHiddenWindow
)
728 gs_classForHiddenWindow
= _T("wxHiddenWindow");
731 wxZeroMemory(wndclass
);
732 wndclass
.lpfnWndProc
= (WNDPROC
)wxExecuteWindowCbk
;
733 wndclass
.hInstance
= wxGetInstance();
734 wndclass
.lpszClassName
= gs_classForHiddenWindow
;
736 if ( !::RegisterClass(&wndclass
) )
738 wxLogLastError(wxT("RegisterClass(hidden window)"));
742 // create a hidden window to receive notification about process
744 HWND hwnd
= ::CreateWindow(gs_classForHiddenWindow
, NULL
,
747 (HMENU
)NULL
, wxGetInstance(), 0);
748 wxASSERT_MSG( hwnd
, wxT("can't create a hidden window for wxExecute") );
751 wxExecuteData
*data
= new wxExecuteData
;
752 data
->hProcess
= pi
.hProcess
;
753 data
->dwProcessId
= pi
.dwProcessId
;
755 data
->state
= (flags
& wxEXEC_SYNC
) != 0;
756 if ( flags
& wxEXEC_SYNC
)
758 // handler may be !NULL for capturing program output, but we don't use
759 // it wxExecuteData struct in this case
760 data
->handler
= NULL
;
764 // may be NULL or not
765 data
->handler
= handler
;
769 HANDLE hThread
= ::CreateThread(NULL
,
776 // resume process we created now - whether the thread creation succeeded or
778 if ( ::ResumeThread(pi
.hThread
) == (DWORD
)-1 )
780 // ignore it - what can we do?
781 wxLogLastError(wxT("ResumeThread in wxExecute"));
784 // close unneeded handle
785 if ( !::CloseHandle(pi
.hThread
) )
786 wxLogLastError(wxT("CloseHandle(hThread)"));
790 wxLogLastError(wxT("CreateThread in wxExecute"));
795 // the process still started up successfully...
796 return pi
.dwProcessId
;
799 ::CloseHandle(hThread
);
802 // second part of DDE hack: now establish the DDE conversation with the
803 // just launched process
804 if ( !ddeServer
.empty() )
808 // give the process the time to init itself
810 // we use a very big timeout hoping that WaitForInputIdle() will return
811 // much sooner, but not INFINITE just in case the process hangs
812 // completely - like this we will regain control sooner or later
813 switch ( ::WaitForInputIdle(pi
.hProcess
, 10000 /* 10 seconds */) )
816 wxFAIL_MSG( _T("unexpected WaitForInputIdle() return code") );
820 wxLogLastError(_T("WaitForInputIdle() in wxExecute"));
823 wxLogDebug(_T("Timeout too small in WaitForInputIdle"));
829 // ok, process ready to accept DDE requests
830 ok
= wxExecuteDDE(ddeServer
, ddeTopic
, ddeCommand
);
835 if ( !(flags
& wxEXEC_SYNC
) )
837 // clean up will be done when the process terminates
840 return pi
.dwProcessId
;
843 // waiting until command executed (disable everything while doing it)
851 // wait until the child process terminates
852 while ( data
->state
)
857 #endif // wxUSE_STREAMS
859 // don't eat 100% of the CPU -- ugly but anything else requires
860 // real async IO which we don't have for the moment
871 DWORD dwExitCode
= data
->dwExitCode
;
874 // return the exit code
877 long instanceID
= WinExec((LPCSTR
) WXSTRINGCAST command
, SW_SHOW
);
879 return flags
& wxEXEC_SYNC
? -1 : 0;
881 if ( flags
& wxEXEC_SYNC
)
887 running
= GetModuleUsage((HINSTANCE
)instanceID
);
895 long wxExecute(char **argv
, int flags
, wxProcess
*handler
)
899 while ( *argv
!= NULL
)
901 command
<< *argv
++ << ' ';
904 command
.RemoveLast();
906 return wxExecute(command
, flags
, handler
);