1 /////////////////////////////////////////////////////////////////////////////
2 // Name: msw/utilsexec.cpp
3 // Purpose: Various utilities
4 // Author: Julian Smart
8 // Copyright: (c) Julian Smart and Markus Holzem
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 ~wxPipeInputStream();
136 virtual bool Eof() const;
139 size_t OnSysRead(void *buffer
, size_t len
);
145 class wxPipeOutputStream
: public wxOutputStream
148 wxPipeOutputStream(HANDLE hOutput
);
149 ~wxPipeOutputStream();
152 size_t OnSysWrite(const void *buffer
, size_t len
);
158 // ==================
160 // ==================
162 wxPipeInputStream::wxPipeInputStream(HANDLE hInput
)
167 wxPipeInputStream::~wxPipeInputStream()
169 ::CloseHandle(m_hInput
);
172 bool wxPipeInputStream::Eof() const
176 // function name is misleading, it works with anon pipes as well
177 DWORD rc
= ::PeekNamedPipe
180 NULL
, 0, // ptr to buffer and its size
181 NULL
, // [out] bytes read
182 &nAvailable
, // [out] bytes available
183 NULL
// [out] bytes left
188 if ( ::GetLastError() != ERROR_BROKEN_PIPE
)
191 wxLogLastError(_T("PeekNamedPipe"));
194 // don't try to continue reading from a pipe if an error occured or if
195 // it had been closed
200 return nAvailable
== 0;
204 size_t wxPipeInputStream::OnSysRead(void *buffer
, size_t len
)
206 // reading from a pipe may block if there is no more data, always check for
208 m_lasterror
= wxSTREAM_NOERROR
;
213 if ( !::ReadFile(m_hInput
, buffer
, len
, &bytesRead
, NULL
) )
215 if ( ::GetLastError() == ERROR_BROKEN_PIPE
)
216 m_lasterror
= wxSTREAM_EOF
;
218 m_lasterror
= wxSTREAM_READ_ERROR
;
224 // ==================
225 // wxPipeOutputStream
226 // ==================
228 wxPipeOutputStream::wxPipeOutputStream(HANDLE hOutput
)
233 wxPipeOutputStream::~wxPipeOutputStream()
235 ::CloseHandle(m_hOutput
);
238 size_t wxPipeOutputStream::OnSysWrite(const void *buffer
, size_t len
)
242 m_lasterror
= wxSTREAM_NOERROR
;
243 if ( !::WriteFile(m_hOutput
, buffer
, len
, &bytesRead
, NULL
) )
245 if ( ::GetLastError() == ERROR_BROKEN_PIPE
)
246 m_lasterror
= wxSTREAM_EOF
;
248 m_lasterror
= wxSTREAM_READ_ERROR
;
256 // ============================================================================
258 // ============================================================================
262 static DWORD __stdcall
wxExecuteThread(void *arg
)
264 wxExecuteData
*data
= (wxExecuteData
*)arg
;
266 WaitForSingleObject(data
->hProcess
, INFINITE
);
269 if ( !GetExitCodeProcess(data
->hProcess
, &data
->dwExitCode
) )
271 wxLogLastError(wxT("GetExitCodeProcess"));
274 wxASSERT_MSG( data
->dwExitCode
!= STILL_ACTIVE
,
275 wxT("process should have terminated") );
277 // send a message indicating process termination to the window
278 SendMessage(data
->hWnd
, wxWM_PROC_TERMINATED
, 0, (LPARAM
)data
);
283 // window procedure of a hidden window which is created just to receive
284 // the notification message when a process exits
285 LRESULT APIENTRY _EXPORT
wxExecuteWindowCbk(HWND hWnd
, UINT message
,
286 WPARAM wParam
, LPARAM lParam
)
288 if ( message
== wxWM_PROC_TERMINATED
)
290 DestroyWindow(hWnd
); // we don't need it any more
292 wxExecuteData
*data
= (wxExecuteData
*)lParam
;
295 data
->handler
->OnTerminate((int)data
->dwProcessId
,
296 (int)data
->dwExitCode
);
301 // we're executing synchronously, tell the waiting thread
302 // that the process finished
307 // asynchronous execution - we should do the clean up
315 return DefWindowProc(hWnd
, message
, wParam
, lParam
);
322 // connect to the given server via DDE and ask it to execute the command
323 static bool wxExecuteDDE(const wxString
& ddeServer
,
324 const wxString
& ddeTopic
,
325 const wxString
& ddeCommand
)
330 wxConnectionBase
*conn
= client
.MakeConnection(_T(""),
337 else // connected to DDE server
339 // the added complication here is that although most
340 // programs use XTYP_EXECUTE for their DDE API, some
341 // important ones - like IE and other MS stuff - use
344 // so we try it first and then the other one if it
348 ok
= conn
->Request(ddeCommand
) != NULL
;
353 // now try execute - but show the errors
354 ok
= conn
->Execute(ddeCommand
);
363 long wxExecute(const wxString
& cmd
, int flags
, wxProcess
*handler
)
365 wxCHECK_MSG( !!cmd
, 0, wxT("empty command in wxExecute") );
370 // DDE hack: this is really not pretty, but we need to allow this for
371 // transparent handling of DDE servers in wxMimeTypesManager. Usually it
372 // returns the command which should be run to view/open/... a file of the
373 // given type. Sometimes, however, this command just launches the server
374 // and an additional DDE request must be made to really open the file. To
375 // keep all this well hidden from the application, we allow a special form
376 // of command: WX_DDE#<command>#DDE_SERVER#DDE_TOPIC#DDE_COMMAND in which
377 // case we execute just <command> and process the rest below
378 wxString ddeServer
, ddeTopic
, ddeCommand
;
379 static const size_t lenDdePrefix
= 7; // strlen("WX_DDE:")
380 if ( cmd
.Left(lenDdePrefix
) == _T("WX_DDE#") )
382 // speed up the concatenations below
383 ddeServer
.reserve(256);
384 ddeTopic
.reserve(256);
385 ddeCommand
.reserve(256);
387 const wxChar
*p
= cmd
.c_str() + 7;
388 while ( *p
&& *p
!= _T('#') )
400 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
403 while ( *p
&& *p
!= _T('#') )
415 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
418 while ( *p
&& *p
!= _T('#') )
430 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
438 // if we want to just launch the program and not wait for its
439 // termination, try to execute DDE command right now, it can succeed if
440 // the process is already running - but as it fails if it's not
441 // running, suppress any errors it might generate
442 if ( !(flags
& wxEXEC_SYNC
) )
445 if ( wxExecuteDDE(ddeServer
, ddeTopic
, ddeCommand
) )
447 // a dummy PID - this is a hack, of course, but it's well worth
448 // it as we don't open a new server each time we're called
449 // which would be quite bad
461 #if defined(__WIN32__) && !defined(__TWIN32__)
463 // the IO redirection is only supported with wxUSE_STREAMS
464 BOOL redirect
= FALSE
;
466 // the first elements are reading ends, the second are the writing ones
467 HANDLE hpipeStdin
[2],
470 HANDLE hpipeStdinWrite
= INVALID_HANDLE_VALUE
;
472 // open the pipes to which child process IO will be redirected if needed
473 if ( handler
&& handler
->IsRedirected() )
475 // default secutiry attributes
476 SECURITY_ATTRIBUTES security
;
478 security
.nLength
= sizeof(security
);
479 security
.lpSecurityDescriptor
= NULL
;
480 security
.bInheritHandle
= TRUE
;
483 if ( !::CreatePipe(&hpipeStdin
[0], &hpipeStdin
[1], &security
, 0) )
485 wxLogSysError(_("Can't create the inter-process read pipe"));
487 // indicate failure: we need to return different error code
488 // depending on the sync flag
489 return flags
& wxEXEC_SYNC
? -1 : 0;
493 if ( !::CreatePipe(&hpipeStdout
[0], &hpipeStdout
[1], &security
, 0) )
495 ::CloseHandle(hpipeStdin
[0]);
496 ::CloseHandle(hpipeStdin
[1]);
498 wxLogSysError(_("Can't create the inter-process write pipe"));
500 return flags
& wxEXEC_SYNC
? -1 : 0;
503 (void)::CreatePipe(&hpipeStderr
[0], &hpipeStderr
[1], &security
, 0);
507 #endif // wxUSE_STREAMS
509 // create the process
517 si
.dwFlags
= STARTF_USESTDHANDLES
;
519 si
.hStdInput
= hpipeStdin
[0];
520 si
.hStdOutput
= hpipeStdout
[1];
521 si
.hStdError
= hpipeStderr
[1];
523 // when the std IO is redirected, we don't show the (console) process
524 // window by default, but this can be overridden by the caller by
525 // specifying wxEXEC_NOHIDE flag
526 if ( !(flags
& wxEXEC_NOHIDE
) )
528 si
.dwFlags
|= STARTF_USESHOWWINDOW
;
529 si
.wShowWindow
= SW_HIDE
;
532 // we must duplicate the handle to the write side of stdin pipe to make
533 // it non inheritable: indeed, we must close hpipeStdin[1] before
534 // launching the child process as otherwise this handle will be
535 // inherited by the child which will never close it and so the pipe
536 // will never be closed and the child will be left stuck in ReadFile()
537 if ( !::DuplicateHandle
543 0, // desired access: unused here
544 FALSE
, // not inherited
545 DUPLICATE_SAME_ACCESS
// same access as for src handle
548 wxLogLastError(_T("DuplicateHandle"));
551 ::CloseHandle(hpipeStdin
[1]);
553 #endif // wxUSE_STREAMS
555 PROCESS_INFORMATION pi
;
556 DWORD dwFlags
= CREATE_DEFAULT_ERROR_MODE
| CREATE_SUSPENDED
;
558 bool ok
= ::CreateProcess
560 NULL
, // application name (use only cmd line)
562 command
.c_str(), // full command line
563 NULL
, // security attributes: defaults for both
564 NULL
, // the process and its main thread
565 redirect
, // inherit handles if we use pipes
566 dwFlags
, // process creation flags
567 NULL
, // environment (use the same)
568 NULL
, // current directory (use the same)
569 &si
, // startup info (unused here)
574 // we can close the pipe ends used by child anyhow
577 ::CloseHandle(hpipeStdin
[0]);
578 ::CloseHandle(hpipeStdout
[1]);
579 ::CloseHandle(hpipeStderr
[1]);
581 #endif // wxUSE_STREAMS
586 // close the other handles too
589 ::CloseHandle(hpipeStdout
[0]);
590 ::CloseHandle(hpipeStderr
[0]);
592 #endif // wxUSE_STREAMS
594 wxLogSysError(_("Execution of command '%s' failed"), command
.c_str());
596 return flags
& wxEXEC_SYNC
? -1 : 0;
602 // We can now initialize the wxStreams
603 wxInputStream
*inStream
= new wxPipeInputStream(hpipeStdout
[0]),
604 *errStream
= new wxPipeInputStream(hpipeStderr
[0]);
605 wxOutputStream
*outStream
= new wxPipeOutputStream(hpipeStdinWrite
);
607 handler
->SetPipeStreams(inStream
, outStream
, errStream
);
609 #endif // wxUSE_STREAMS
611 // register the class for the hidden window used for the notifications
612 if ( !gs_classForHiddenWindow
)
614 gs_classForHiddenWindow
= _T("wxHiddenWindow");
617 wxZeroMemory(wndclass
);
618 wndclass
.lpfnWndProc
= (WNDPROC
)wxExecuteWindowCbk
;
619 wndclass
.hInstance
= wxGetInstance();
620 wndclass
.lpszClassName
= gs_classForHiddenWindow
;
622 if ( !::RegisterClass(&wndclass
) )
624 wxLogLastError(wxT("RegisterClass(hidden window)"));
628 // create a hidden window to receive notification about process
630 HWND hwnd
= ::CreateWindow(gs_classForHiddenWindow
, NULL
,
633 (HMENU
)NULL
, wxGetInstance(), 0);
634 wxASSERT_MSG( hwnd
, wxT("can't create a hidden window for wxExecute") );
637 wxExecuteData
*data
= new wxExecuteData
;
638 data
->hProcess
= pi
.hProcess
;
639 data
->dwProcessId
= pi
.dwProcessId
;
641 data
->state
= (flags
& wxEXEC_SYNC
) != 0;
642 if ( flags
& wxEXEC_SYNC
)
644 // handler may be !NULL for capturing program output, but we don't use
645 // it wxExecuteData struct in this case
646 data
->handler
= NULL
;
650 // may be NULL or not
651 data
->handler
= handler
;
655 HANDLE hThread
= ::CreateThread(NULL
,
662 // resume process we created now - whether the thread creation succeeded or
664 if ( ::ResumeThread(pi
.hThread
) == (DWORD
)-1 )
666 // ignore it - what can we do?
667 wxLogLastError(wxT("ResumeThread in wxExecute"));
670 // close unneeded handle
671 if ( !::CloseHandle(pi
.hThread
) )
672 wxLogLastError(wxT("CloseHandle(hThread)"));
676 wxLogLastError(wxT("CreateThread in wxExecute"));
681 // the process still started up successfully...
682 return pi
.dwProcessId
;
685 ::CloseHandle(hThread
);
688 // second part of DDE hack: now establish the DDE conversation with the
689 // just launched process
690 if ( !ddeServer
.empty() )
694 // give the process the time to init itself
696 // we use a very big timeout hoping that WaitForInputIdle() will return
697 // much sooner, but not INFINITE just in case the process hangs
698 // completely - like this we will regain control sooner or later
699 switch ( ::WaitForInputIdle(pi
.hProcess
, 10000 /* 10 seconds */) )
702 wxFAIL_MSG( _T("unexpected WaitForInputIdle() return code") );
706 wxLogLastError(_T("WaitForInputIdle() in wxExecute"));
709 wxLogDebug(_T("Timeout too small in WaitForInputIdle"));
715 // ok, process ready to accept DDE requests
716 ok
= wxExecuteDDE(ddeServer
, ddeTopic
, ddeCommand
);
721 if ( !(flags
& wxEXEC_SYNC
) )
723 // clean up will be done when the process terminates
726 return pi
.dwProcessId
;
729 // waiting until command executed (disable everything while doing it)
737 while ( data
->state
)
739 // don't take 100% of the CPU
748 DWORD dwExitCode
= data
->dwExitCode
;
751 // return the exit code
754 long instanceID
= WinExec((LPCSTR
) WXSTRINGCAST command
, SW_SHOW
);
756 return flags
& wxEXEC_SYNC
? -1 : 0;
758 if ( flags
& wxEXEC_SYNC
)
764 running
= GetModuleUsage((HINSTANCE
)instanceID
);
772 long wxExecute(char **argv
, int flags
, wxProcess
*handler
)
776 while ( *argv
!= NULL
)
778 command
<< *argv
++ << ' ';
781 command
.RemoveLast();
783 return wxExecute(command
, flags
, handler
);