]> git.saurik.com Git - wxWidgets.git/blame - src/msw/utilsexc.cpp
Removed code duplication introduced during wxUniv merge in 1.132
[wxWidgets.git] / src / msw / utilsexc.cpp
CommitLineData
32592631 1/////////////////////////////////////////////////////////////////////////////
b568d04f 2// Name: msw/utilsexec.cpp
79066131 3// Purpose: wxExecute implementation for MSW
32592631
GL
4// Author: Julian Smart
5// Modified by:
6// Created: 04/01/98
7// RCS-ID: $Id$
79066131 8// Copyright: (c) 1998-2002 wxWindows dev team
6c9a19aa 9// Licence: wxWindows licence
32592631
GL
10/////////////////////////////////////////////////////////////////////////////
11
b568d04f
VZ
12// ============================================================================
13// declarations
14// ============================================================================
15
16// ----------------------------------------------------------------------------
17// headers
18// ----------------------------------------------------------------------------
19
14f355c2 20#if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
b568d04f 21 #pragma implementation
32592631
GL
22#endif
23
24// For compilers that support precompilation, includes "wx.h".
25#include "wx/wxprec.h"
26
27#ifdef __BORLANDC__
b568d04f 28 #pragma hdrstop
32592631
GL
29#endif
30
31#ifndef WX_PRECOMP
b568d04f
VZ
32 #include "wx/utils.h"
33 #include "wx/app.h"
34 #include "wx/intl.h"
068a7cfe 35 #include "wx/log.h"
2ae8a353 36#endif
32592631 37
eccd1992
VZ
38#include "wx/stream.h"
39#include "wx/process.h"
dbeac4bd 40
e2478fde
VZ
41#include "wx/apptrait.h"
42
eccd1992
VZ
43#include "wx/module.h"
44
32592631 45#include "wx/msw/private.h"
dbeac4bd 46
32592631
GL
47#include <ctype.h>
48
4676948b 49#if !defined(__GNUWIN32__) && !defined(__SALFORDC__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
b568d04f 50 #include <direct.h>
17dff81c 51#ifndef __MWERKS__
b568d04f 52 #include <dos.h>
32592631 53#endif
17dff81c 54#endif
32592631 55
b39dbf34 56#if defined(__GNUWIN32__)
b568d04f
VZ
57 #include <sys/unistd.h>
58 #include <sys/stat.h>
57c208c5 59#endif
32592631 60
eccd1992
VZ
61#if !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
62 #ifndef __UNIX__
63 #include <io.h>
64 #endif
32592631 65
eccd1992
VZ
66 #ifndef __GNUWIN32__
67 #include <shellapi.h>
68 #endif
32592631
GL
69#endif
70
71#include <stdio.h>
72#include <stdlib.h>
73#include <string.h>
74#ifndef __WATCOMC__
3f4a0c5b
VZ
75 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
76 #include <errno.h>
77 #endif
32592631
GL
78#endif
79#include <stdarg.h>
80
731dd422
VZ
81#if wxUSE_IPC
82 #include "wx/dde.h" // for WX_DDE hack in wxExecute
83#endif // wxUSE_IPC
5bd3a2da 84
eccd1992 85// implemented in utils.cpp
487f2d58 86extern "C" WXDLLIMPEXP_BASE HWND
eccd1992
VZ
87wxCreateHiddenWindow(LPCTSTR *pclassname, LPCTSTR classname, WNDPROC wndproc);
88
b568d04f
VZ
89// ----------------------------------------------------------------------------
90// constants
91// ----------------------------------------------------------------------------
92
cb6827a8
VZ
93// this message is sent when the process we're waiting for terminates
94#define wxWM_PROC_TERMINATED (WM_USER + 10000)
32592631 95
b568d04f
VZ
96// ----------------------------------------------------------------------------
97// this module globals
98// ----------------------------------------------------------------------------
99
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
eccd1992 103static const wxChar *wxMSWEXEC_WNDCLASSNAME = wxT("_wxExecute_Internal_Class");
b568d04f
VZ
104static const wxChar *gs_classForHiddenWindow = NULL;
105
106// ----------------------------------------------------------------------------
107// private types
108// ----------------------------------------------------------------------------
109
cb6827a8
VZ
110// structure describing the process we're being waiting for
111struct wxExecuteData
112{
113public:
114 ~wxExecuteData()
115 {
750b78ba 116#ifndef __WIN16__
cb6827a8
VZ
117 if ( !::CloseHandle(hProcess) )
118 {
f6bcfd97 119 wxLogLastError(wxT("CloseHandle(hProcess)"));
cb6827a8 120 }
750b78ba 121#endif
cb6827a8
VZ
122 }
123
124 HWND hWnd; // window to send wxWM_PROC_TERMINATED to
125 HANDLE hProcess; // handle of the process
126 DWORD dwProcessId; // pid of the process
127 wxProcess *handler;
128 DWORD dwExitCode; // the exit code of the process
129 bool state; // set to FALSE when the process finishes
32592631
GL
130};
131
eccd1992
VZ
132class wxExecuteModule : public wxModule
133{
134public:
135 virtual bool OnInit() { return true; }
136 virtual void OnExit()
137 {
138 if ( *gs_classForHiddenWindow )
139 {
140 if ( !::UnregisterClass(wxMSWEXEC_WNDCLASSNAME, wxGetInstance()) )
141 {
142 wxLogLastError(_T("UnregisterClass(wxExecClass)"));
143 }
144
145 gs_classForHiddenWindow = NULL;
146 }
147 }
148
149private:
150 DECLARE_DYNAMIC_CLASS(wxExecuteModule)
151};
152
153#if wxUSE_STREAMS && !defined(__WXWINCE__)
8b33ae2d 154
8b33ae2d
GL
155// ----------------------------------------------------------------------------
156// wxPipeStreams
157// ----------------------------------------------------------------------------
158
f6bcfd97
BP
159class wxPipeInputStream: public wxInputStream
160{
8b33ae2d
GL
161public:
162 wxPipeInputStream(HANDLE hInput);
79066131 163 virtual ~wxPipeInputStream();
8b33ae2d 164
79066131
VZ
165 // returns TRUE if the pipe is still opened
166 bool IsOpened() const { return m_hInput != INVALID_HANDLE_VALUE; }
167
168 // returns TRUE if there is any data to be read from the pipe
2b5f62a0 169 virtual bool CanRead() const;
f6bcfd97 170
8b33ae2d
GL
171protected:
172 size_t OnSysRead(void *buffer, size_t len);
173
174protected:
175 HANDLE m_hInput;
22f3361e
VZ
176
177 DECLARE_NO_COPY_CLASS(wxPipeInputStream)
8b33ae2d
GL
178};
179
f6bcfd97
BP
180class wxPipeOutputStream: public wxOutputStream
181{
8b33ae2d
GL
182public:
183 wxPipeOutputStream(HANDLE hOutput);
79066131 184 virtual ~wxPipeOutputStream();
8b33ae2d
GL
185
186protected:
187 size_t OnSysWrite(const void *buffer, size_t len);
188
189protected:
190 HANDLE m_hOutput;
22f3361e
VZ
191
192 DECLARE_NO_COPY_CLASS(wxPipeOutputStream)
8b33ae2d
GL
193};
194
79066131
VZ
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"
198
199// ----------------------------------------------------------------------------
200// wxPipe represents a Win32 anonymous pipe
201// ----------------------------------------------------------------------------
202
203class wxPipe
204{
205public:
206 // the symbolic names for the pipe ends
207 enum Direction
208 {
209 Read,
210 Write
211 };
212
213 // default ctor doesn't do anything
214 wxPipe() { m_handles[Read] = m_handles[Write] = INVALID_HANDLE_VALUE; }
215
216 // create the pipe, return TRUE if ok, FALSE on error
217 bool Create()
218 {
219 // default secutiry attributes
220 SECURITY_ATTRIBUTES security;
221
222 security.nLength = sizeof(security);
223 security.lpSecurityDescriptor = NULL;
224 security.bInheritHandle = TRUE; // to pass it to the child
225
226 if ( !::CreatePipe(&m_handles[0], &m_handles[1], &security, 0) )
227 {
228 wxLogSysError(_("Failed to create an anonymous pipe"));
229
230 return FALSE;
231 }
232
233 return TRUE;
234 }
235
236 // return TRUE if we were created successfully
237 bool IsOk() const { return m_handles[Read] != INVALID_HANDLE_VALUE; }
238
239 // return the descriptor for one of the pipe ends
240 HANDLE operator[](Direction which) const
241 {
242 wxASSERT_MSG( which >= 0 && (size_t)which < WXSIZEOF(m_handles),
243 _T("invalid pipe index") );
244
245 return m_handles[which];
246 }
247
248 // detach a descriptor, meaning that the pipe dtor won't close it, and
249 // return it
250 HANDLE Detach(Direction which)
251 {
252 wxASSERT_MSG( which >= 0 && (size_t)which < WXSIZEOF(m_handles),
253 _T("invalid pipe index") );
254
255 HANDLE handle = m_handles[which];
256 m_handles[which] = INVALID_HANDLE_VALUE;
257
258 return handle;
259 }
260
261 // close the pipe descriptors
262 void Close()
263 {
264 for ( size_t n = 0; n < WXSIZEOF(m_handles); n++ )
265 {
266 if ( m_handles[n] != INVALID_HANDLE_VALUE )
267 {
268 ::CloseHandle(m_handles[n]);
269 m_handles[n] = INVALID_HANDLE_VALUE;
270 }
271 }
272 }
273
274 // dtor closes the pipe descriptors
275 ~wxPipe() { Close(); }
276
277private:
278 HANDLE m_handles[2];
279};
280
281#endif // wxUSE_STREAMS
282
283// ============================================================================
284// implementation
285// ============================================================================
286
79066131
VZ
287// ----------------------------------------------------------------------------
288// process termination detecting support
289// ----------------------------------------------------------------------------
290
291// thread function for the thread monitoring the process termination
292static DWORD __stdcall wxExecuteThread(void *arg)
293{
45d5a0c6 294 wxExecuteData * const data = (wxExecuteData *)arg;
79066131
VZ
295
296 if ( ::WaitForSingleObject(data->hProcess, INFINITE) != WAIT_OBJECT_0 )
297 {
298 wxLogDebug(_T("Waiting for the process termination failed!"));
299 }
300
301 // get the exit code
302 if ( !::GetExitCodeProcess(data->hProcess, &data->dwExitCode) )
303 {
304 wxLogLastError(wxT("GetExitCodeProcess"));
305 }
306
307 wxASSERT_MSG( data->dwExitCode != STILL_ACTIVE,
308 wxT("process should have terminated") );
309
310 // send a message indicating process termination to the window
311 ::SendMessage(data->hWnd, wxWM_PROC_TERMINATED, 0, (LPARAM)data);
312
313 return 0;
314}
315
316// window procedure of a hidden window which is created just to receive
317// the notification message when a process exits
318LRESULT APIENTRY _EXPORT wxExecuteWindowCbk(HWND hWnd, UINT message,
319 WPARAM wParam, LPARAM lParam)
320{
321 if ( message == wxWM_PROC_TERMINATED )
322 {
323 DestroyWindow(hWnd); // we don't need it any more
324
45d5a0c6 325 wxExecuteData * const data = (wxExecuteData *)lParam;
79066131
VZ
326 if ( data->handler )
327 {
328 data->handler->OnTerminate((int)data->dwProcessId,
329 (int)data->dwExitCode);
330 }
331
332 if ( data->state )
333 {
334 // we're executing synchronously, tell the waiting thread
335 // that the process finished
336 data->state = 0;
337 }
338 else
339 {
340 // asynchronous execution - we should do the clean up
341 delete data;
342 }
343
344 return 0;
345 }
346 else
347 {
45d5a0c6 348 return ::DefWindowProc(hWnd, message, wParam, lParam);
79066131
VZ
349 }
350}
351
352// ============================================================================
353// implementation of IO redirection support classes
354// ============================================================================
355
4676948b 356#if wxUSE_STREAMS && !defined(__WXWINCE__)
79066131
VZ
357
358// ----------------------------------------------------------------------------
359// wxPipeInputStreams
360// ----------------------------------------------------------------------------
8b33ae2d
GL
361
362wxPipeInputStream::wxPipeInputStream(HANDLE hInput)
363{
364 m_hInput = hInput;
cd6ce4a9 365}
8b33ae2d
GL
366
367wxPipeInputStream::~wxPipeInputStream()
368{
79066131
VZ
369 if ( m_hInput != INVALID_HANDLE_VALUE )
370 ::CloseHandle(m_hInput);
8b33ae2d
GL
371}
372
2b5f62a0 373bool wxPipeInputStream::CanRead() const
8b33ae2d 374{
79066131
VZ
375 if ( !IsOpened() )
376 return FALSE;
377
f6bcfd97
BP
378 DWORD nAvailable;
379
380 // function name is misleading, it works with anon pipes as well
381 DWORD rc = ::PeekNamedPipe
382 (
383 m_hInput, // handle
384 NULL, 0, // ptr to buffer and its size
385 NULL, // [out] bytes read
386 &nAvailable, // [out] bytes available
387 NULL // [out] bytes left
388 );
389
390 if ( !rc )
391 {
392 if ( ::GetLastError() != ERROR_BROKEN_PIPE )
393 {
394 // unexpected error
395 wxLogLastError(_T("PeekNamedPipe"));
396 }
8b33ae2d 397
f6bcfd97
BP
398 // don't try to continue reading from a pipe if an error occured or if
399 // it had been closed
79066131
VZ
400 ::CloseHandle(m_hInput);
401
2b5f62a0 402 wxPipeInputStream *self = wxConstCast(this, wxPipeInputStream);
79066131 403
2b5f62a0
VZ
404 self->m_hInput = INVALID_HANDLE_VALUE;
405 self->m_lasterror = wxSTREAM_EOF;
406
407 nAvailable = 0;
f6bcfd97 408 }
79066131
VZ
409
410 return nAvailable != 0;
f6bcfd97
BP
411}
412
413size_t wxPipeInputStream::OnSysRead(void *buffer, size_t len)
414{
2b5f62a0 415 if ( !IsOpened() )
79066131
VZ
416 {
417 m_lasterror = wxSTREAM_EOF;
418
f6bcfd97 419 return 0;
79066131
VZ
420 }
421
f6bcfd97
BP
422 DWORD bytesRead;
423 if ( !::ReadFile(m_hInput, buffer, len, &bytesRead, NULL) )
424 {
2b5f62a0
VZ
425 m_lasterror = ::GetLastError() == ERROR_BROKEN_PIPE
426 ? wxSTREAM_EOF
427 : wxSTREAM_READ_ERROR;
8b33ae2d 428 }
f6bcfd97 429
2b5f62a0 430 // bytesRead is set to 0, as desired, if an error occured
8b33ae2d
GL
431 return bytesRead;
432}
433
79066131 434// ----------------------------------------------------------------------------
8b33ae2d 435// wxPipeOutputStream
79066131 436// ----------------------------------------------------------------------------
8b33ae2d
GL
437
438wxPipeOutputStream::wxPipeOutputStream(HANDLE hOutput)
439{
440 m_hOutput = hOutput;
cd6ce4a9 441}
8b33ae2d
GL
442
443wxPipeOutputStream::~wxPipeOutputStream()
444{
445 ::CloseHandle(m_hOutput);
446}
447
448size_t wxPipeOutputStream::OnSysWrite(const void *buffer, size_t len)
449{
2b5f62a0 450 DWORD bytesWritten;
8b33ae2d 451
2b5f62a0
VZ
452 m_lasterror = wxSTREAM_NO_ERROR;
453 if ( !::WriteFile(m_hOutput, buffer, len, &bytesWritten, NULL) )
f6bcfd97 454 {
2b5f62a0
VZ
455 m_lasterror = ::GetLastError() == ERROR_BROKEN_PIPE
456 ? wxSTREAM_EOF
457 : wxSTREAM_WRITE_ERROR;
8b33ae2d 458 }
f6bcfd97 459
2b5f62a0 460 return bytesWritten;
8b33ae2d
GL
461}
462
79066131
VZ
463#endif // wxUSE_STREAMS
464
b568d04f 465// ============================================================================
79066131 466// wxExecute functions family
b568d04f 467// ============================================================================
5260b1c5 468
ca289436
VZ
469#if wxUSE_IPC
470
471// connect to the given server via DDE and ask it to execute the command
472static bool wxExecuteDDE(const wxString& ddeServer,
473 const wxString& ddeTopic,
474 const wxString& ddeCommand)
475{
999836aa 476 bool ok wxDUMMY_INITIALIZE(false);
ca289436
VZ
477
478 wxDDEClient client;
fda7962d 479 wxConnectionBase *conn = client.MakeConnection(wxEmptyString,
ca289436
VZ
480 ddeServer,
481 ddeTopic);
482 if ( !conn )
483 {
484 ok = FALSE;
485 }
486 else // connected to DDE server
487 {
4dd03db9
VZ
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!
ca289436 491 //
4dd03db9
VZ
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
ca289436 495 {
4dd03db9 496 // we're prepared for this one to fail, so don't show errors
ca289436 497 wxLogNull noErrors;
4dd03db9
VZ
498
499 ok = conn->Request(ddeCommand) != NULL;
ca289436
VZ
500 }
501
502 if ( !ok )
503 {
4dd03db9
VZ
504 // now try execute -- but show the errors
505 ok = conn->Execute(ddeCommand);
ca289436
VZ
506 }
507 }
508
509 return ok;
510}
511
512#endif // wxUSE_IPC
513
fbf456aa 514long wxExecute(const wxString& cmd, int flags, wxProcess *handler)
32592631 515{
5bd3a2da
VZ
516 wxCHECK_MSG( !!cmd, 0, wxT("empty command in wxExecute") );
517
647b8e37
VZ
518#if wxUSE_THREADS
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
525
039f62f4 526 wxString command;
6ba63600 527
731dd422 528#if wxUSE_IPC
5bd3a2da
VZ
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
6ba63600 535 // of command: WX_DDE#<command>#DDE_SERVER#DDE_TOPIC#DDE_COMMAND in which
5bd3a2da 536 // case we execute just <command> and process the rest below
039f62f4 537 wxString ddeServer, ddeTopic, ddeCommand;
5bd3a2da
VZ
538 static const size_t lenDdePrefix = 7; // strlen("WX_DDE:")
539 if ( cmd.Left(lenDdePrefix) == _T("WX_DDE#") )
540 {
ca289436
VZ
541 // speed up the concatenations below
542 ddeServer.reserve(256);
543 ddeTopic.reserve(256);
544 ddeCommand.reserve(256);
545
5bd3a2da
VZ
546 const wxChar *p = cmd.c_str() + 7;
547 while ( *p && *p != _T('#') )
548 {
549 command += *p++;
550 }
551
552 if ( *p )
553 {
554 // skip '#'
555 p++;
556 }
557 else
558 {
559 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
560 }
561
562 while ( *p && *p != _T('#') )
563 {
564 ddeServer += *p++;
565 }
566
567 if ( *p )
568 {
569 // skip '#'
570 p++;
571 }
572 else
573 {
574 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
575 }
576
577 while ( *p && *p != _T('#') )
578 {
579 ddeTopic += *p++;
580 }
581
582 if ( *p )
583 {
584 // skip '#'
585 p++;
586 }
587 else
588 {
589 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
590 }
591
592 while ( *p )
593 {
594 ddeCommand += *p++;
595 }
6ba63600 596
ca289436
VZ
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
fbf456aa 601 if ( !(flags & wxEXEC_SYNC) )
6ba63600 602 {
ca289436
VZ
603 wxLogNull noErrors;
604 if ( wxExecuteDDE(ddeServer, ddeTopic, ddeCommand) )
605 {
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
609 return -1;
610 }
6ba63600 611 }
5bd3a2da
VZ
612 }
613 else
731dd422 614#endif // wxUSE_IPC
5bd3a2da
VZ
615 {
616 // no DDE
617 command = cmd;
618 }
32592631 619
f6bcfd97
BP
620 // the IO redirection is only supported with wxUSE_STREAMS
621 BOOL redirect = FALSE;
79066131 622
4676948b 623#if wxUSE_STREAMS && !defined(__WXWINCE__)
79066131
VZ
624 wxPipe pipeIn, pipeOut, pipeErr;
625
626 // we'll save here the copy of pipeIn[Write]
33ac7e6f 627 HANDLE hpipeStdinWrite = INVALID_HANDLE_VALUE;
8b33ae2d 628
cd6ce4a9 629 // open the pipes to which child process IO will be redirected if needed
cd6ce4a9
VZ
630 if ( handler && handler->IsRedirected() )
631 {
79066131
VZ
632 // create pipes for redirecting stdin, stdout and stderr
633 if ( !pipeIn.Create() || !pipeOut.Create() || !pipeErr.Create() )
cd6ce4a9 634 {
79066131 635 wxLogSysError(_("Failed to redirect the child process IO"));
8b33ae2d 636
fbf456aa
VZ
637 // indicate failure: we need to return different error code
638 // depending on the sync flag
639 return flags & wxEXEC_SYNC ? -1 : 0;
8b33ae2d
GL
640 }
641
f6bcfd97 642 redirect = TRUE;
8b33ae2d 643 }
f6bcfd97 644#endif // wxUSE_STREAMS
5bd3a2da 645
cb6827a8
VZ
646 // create the process
647 STARTUPINFO si;
11c7d5b6 648 wxZeroMemory(si);
cb6827a8
VZ
649 si.cb = sizeof(si);
650
4676948b 651#if wxUSE_STREAMS && !defined(__WXWINCE__)
f6bcfd97 652 if ( redirect )
cb6827a8 653 {
fbf456aa 654 si.dwFlags = STARTF_USESTDHANDLES;
f6bcfd97 655
79066131
VZ
656 si.hStdInput = pipeIn[wxPipe::Read];
657 si.hStdOutput = pipeOut[wxPipe::Write];
658 si.hStdError = pipeErr[wxPipe::Write];
f6bcfd97 659
fbf456aa
VZ
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) )
664 {
665 si.dwFlags |= STARTF_USESHOWWINDOW;
666 si.wShowWindow = SW_HIDE;
667 }
f6bcfd97
BP
668
669 // we must duplicate the handle to the write side of stdin pipe to make
79066131
VZ
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
f6bcfd97
BP
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()
79066131 674 HANDLE pipeInWrite = pipeIn.Detach(wxPipe::Write);
f6bcfd97
BP
675 if ( !::DuplicateHandle
676 (
79066131
VZ
677 ::GetCurrentProcess(),
678 pipeInWrite,
679 ::GetCurrentProcess(),
f6bcfd97
BP
680 &hpipeStdinWrite,
681 0, // desired access: unused here
682 FALSE, // not inherited
683 DUPLICATE_SAME_ACCESS // same access as for src handle
684 ) )
cd6ce4a9 685 {
f6bcfd97 686 wxLogLastError(_T("DuplicateHandle"));
8b33ae2d 687 }
cd6ce4a9 688
79066131 689 ::CloseHandle(pipeInWrite);
f6bcfd97
BP
690 }
691#endif // wxUSE_STREAMS
cb6827a8 692
f6bcfd97 693 PROCESS_INFORMATION pi;
4676948b
JS
694 DWORD dwFlags = CREATE_SUSPENDED;
695#ifndef __WXWINCE__
696 dwFlags |= CREATE_DEFAULT_ERROR_MODE ;
697#endif
f6bcfd97
BP
698
699 bool ok = ::CreateProcess
700 (
701 NULL, // application name (use only cmd line)
702 (wxChar *)
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)
711 &pi // process info
712 ) != 0;
713
4676948b 714#if wxUSE_STREAMS && !defined(__WXWINCE__)
f6bcfd97
BP
715 // we can close the pipe ends used by child anyhow
716 if ( redirect )
717 {
79066131
VZ
718 ::CloseHandle(pipeIn.Detach(wxPipe::Read));
719 ::CloseHandle(pipeOut.Detach(wxPipe::Write));
720 ::CloseHandle(pipeErr.Detach(wxPipe::Write));
cb6827a8 721 }
f6bcfd97 722#endif // wxUSE_STREAMS
cb6827a8 723
f6bcfd97 724 if ( !ok )
5e1febfa 725 {
4676948b 726#if wxUSE_STREAMS && !defined(__WXWINCE__)
f6bcfd97
BP
727 // close the other handles too
728 if ( redirect )
5e1febfa 729 {
79066131
VZ
730 ::CloseHandle(pipeOut.Detach(wxPipe::Read));
731 ::CloseHandle(pipeErr.Detach(wxPipe::Read));
5e1febfa 732 }
f6bcfd97 733#endif // wxUSE_STREAMS
5e1febfa 734
f6bcfd97
BP
735 wxLogSysError(_("Execution of command '%s' failed"), command.c_str());
736
fbf456aa 737 return flags & wxEXEC_SYNC ? -1 : 0;
f6bcfd97 738 }
8b33ae2d 739
4676948b 740#if wxUSE_STREAMS && !defined(__WXWINCE__)
79066131
VZ
741 // the input buffer bufOut is connected to stdout, this is why it is
742 // called bufOut and not bufIn
743 wxStreamTempInputBuffer bufOut,
744 bufErr;
745
f6bcfd97
BP
746 if ( redirect )
747 {
8b33ae2d 748 // We can now initialize the wxStreams
79066131
VZ
749 wxPipeInputStream *
750 outStream = new wxPipeInputStream(pipeOut.Detach(wxPipe::Read));
751 wxPipeInputStream *
752 errStream = new wxPipeInputStream(pipeErr.Detach(wxPipe::Read));
753 wxPipeOutputStream *
754 inStream = new wxPipeOutputStream(hpipeStdinWrite);
755
756 handler->SetPipeStreams(outStream, inStream, errStream);
8b33ae2d 757
79066131
VZ
758 bufOut.Init(outStream);
759 bufErr.Init(errStream);
8b33ae2d 760 }
f6bcfd97 761#endif // wxUSE_STREAMS
8b33ae2d 762
cb6827a8
VZ
763 // create a hidden window to receive notification about process
764 // termination
eccd1992
VZ
765 HWND hwnd = wxCreateHiddenWindow
766 (
767 &gs_classForHiddenWindow,
768 wxMSWEXEC_WNDCLASSNAME,
769 (WNDPROC)wxExecuteWindowCbk
770 );
771
223d09f6 772 wxASSERT_MSG( hwnd, wxT("can't create a hidden window for wxExecute") );
e6045e08 773
cb6827a8
VZ
774 // Alloc data
775 wxExecuteData *data = new wxExecuteData;
776 data->hProcess = pi.hProcess;
777 data->dwProcessId = pi.dwProcessId;
778 data->hWnd = hwnd;
fbf456aa
VZ
779 data->state = (flags & wxEXEC_SYNC) != 0;
780 if ( flags & wxEXEC_SYNC )
e6045e08 781 {
5e1febfa
VZ
782 // handler may be !NULL for capturing program output, but we don't use
783 // it wxExecuteData struct in this case
e6045e08
VZ
784 data->handler = NULL;
785 }
786 else
787 {
788 // may be NULL or not
789 data->handler = handler;
790 }
cb6827a8
VZ
791
792 DWORD tid;
793 HANDLE hThread = ::CreateThread(NULL,
794 0,
19193a2c 795 wxExecuteThread,
cb6827a8
VZ
796 (void *)data,
797 0,
798 &tid);
799
0d7ea902
VZ
800 // resume process we created now - whether the thread creation succeeded or
801 // not
802 if ( ::ResumeThread(pi.hThread) == (DWORD)-1 )
803 {
804 // ignore it - what can we do?
f6bcfd97 805 wxLogLastError(wxT("ResumeThread in wxExecute"));
0d7ea902
VZ
806 }
807
808 // close unneeded handle
809 if ( !::CloseHandle(pi.hThread) )
f6bcfd97 810 wxLogLastError(wxT("CloseHandle(hThread)"));
0d7ea902 811
cb6827a8
VZ
812 if ( !hThread )
813 {
f6bcfd97 814 wxLogLastError(wxT("CreateThread in wxExecute"));
cb6827a8
VZ
815
816 DestroyWindow(hwnd);
817 delete data;
818
819 // the process still started up successfully...
820 return pi.dwProcessId;
821 }
e6045e08 822
f6bcfd97
BP
823 ::CloseHandle(hThread);
824
4676948b 825#if wxUSE_IPC && !defined(__WXWINCE__)
5bd3a2da
VZ
826 // second part of DDE hack: now establish the DDE conversation with the
827 // just launched process
ca289436 828 if ( !ddeServer.empty() )
5bd3a2da 829 {
ca289436
VZ
830 bool ok;
831
832 // give the process the time to init itself
833 //
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 */) )
6ba63600 838 {
ca289436
VZ
839 default:
840 wxFAIL_MSG( _T("unexpected WaitForInputIdle() return code") );
841 // fall through
6ba63600 842
ca289436
VZ
843 case -1:
844 wxLogLastError(_T("WaitForInputIdle() in wxExecute"));
6ba63600 845
ca289436
VZ
846 case WAIT_TIMEOUT:
847 wxLogDebug(_T("Timeout too small in WaitForInputIdle"));
848
849 ok = FALSE;
850 break;
851
852 case 0:
853 // ok, process ready to accept DDE requests
854 ok = wxExecuteDDE(ddeServer, ddeTopic, ddeCommand);
6ba63600 855 }
1b47bebc
VZ
856
857 if ( !ok )
858 {
859 wxLogDebug(_T("Failed to send DDE request to the process \"%s\"."),
860 cmd.c_str());
861 }
5bd3a2da 862 }
731dd422 863#endif // wxUSE_IPC
5bd3a2da 864
fbf456aa 865 if ( !(flags & wxEXEC_SYNC) )
cb6827a8
VZ
866 {
867 // clean up will be done when the process terminates
e6045e08
VZ
868
869 // return the pid
cb6827a8
VZ
870 return pi.dwProcessId;
871 }
e6045e08 872
e2478fde
VZ
873 wxAppTraits *traits = wxTheApp ? wxTheApp->GetTraits() : NULL;
874 wxCHECK_MSG( traits, -1, _T("no wxAppTraits in wxExecute()?") );
875
068a7cfe 876 // disable all app windows while waiting for the child process to finish
e2478fde
VZ
877 void *cookie = traits->BeforeChildWaitLoop();
878
879 // wait until the child process terminates
880 while ( data->state )
881 {
4676948b 882#if wxUSE_STREAMS && !defined(__WXWINCE__)
e2478fde
VZ
883 bufOut.Update();
884 bufErr.Update();
79066131
VZ
885#endif // wxUSE_STREAMS
886
e2478fde
VZ
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
889 ::Sleep(50);
e6045e08 890
e2478fde
VZ
891 // we must process messages or we'd never get wxWM_PROC_TERMINATED
892 traits->AlwaysYield();
cd6ce4a9 893 }
068a7cfe 894
e2478fde 895 traits->AfterChildWaitLoop(cookie);
0d7ea902 896
e6045e08 897 DWORD dwExitCode = data->dwExitCode;
cb6827a8
VZ
898 delete data;
899
e6045e08
VZ
900 // return the exit code
901 return dwExitCode;
32592631 902}
c740f496 903
0493ba13 904long wxExecute(wxChar **argv, int flags, wxProcess *handler)
c740f496 905{
cb6827a8 906 wxString command;
e6045e08 907
0493ba13 908 for ( ;; )
cb6827a8 909 {
0493ba13
VZ
910 command += *argv++;
911 if ( !*argv )
912 break;
cb6827a8 913
0493ba13
VZ
914 command += _T(' ');
915 }
cb6827a8 916
fbf456aa 917 return wxExecute(command, flags, handler);
c740f496 918}
006162a9 919