]> git.saurik.com Git - wxWidgets.git/blame - src/msw/utilsexc.cpp
Move POSIX implementation of wxThread::Create() to wxThreadInternal.
[wxWidgets.git] / src / msw / utilsexc.cpp
CommitLineData
32592631 1/////////////////////////////////////////////////////////////////////////////
9cd03a43 2// Name: src/msw/utilsexc.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$
77ffb593 8// Copyright: (c) 1998-2002 wxWidgets dev team
65571936 9// Licence: wxWindows licence
32592631
GL
10/////////////////////////////////////////////////////////////////////////////
11
b568d04f
VZ
12// ============================================================================
13// declarations
14// ============================================================================
15
16// ----------------------------------------------------------------------------
17// headers
18// ----------------------------------------------------------------------------
19
32592631
GL
20// For compilers that support precompilation, includes "wx.h".
21#include "wx/wxprec.h"
22
23#ifdef __BORLANDC__
b568d04f 24 #pragma hdrstop
32592631
GL
25#endif
26
27#ifndef WX_PRECOMP
b568d04f
VZ
28 #include "wx/utils.h"
29 #include "wx/app.h"
30 #include "wx/intl.h"
068a7cfe 31 #include "wx/log.h"
530ecef0
WS
32 #if wxUSE_STREAMS
33 #include "wx/stream.h"
34 #endif
02761f6c 35 #include "wx/module.h"
2ae8a353 36#endif
32592631 37
eccd1992 38#include "wx/process.h"
204abcd4 39#include "wx/thread.h"
e2478fde 40#include "wx/apptrait.h"
dbbcfbb6 41#include "wx/evtloop.h"
5a8561fc 42#include "wx/vector.h"
e2478fde 43
eccd1992 44
32592631 45#include "wx/msw/private.h"
dbeac4bd 46
32592631
GL
47#include <ctype.h>
48
f172cb82 49#if !defined(__GNUWIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
b568d04f 50 #include <direct.h>
b568d04f 51 #include <dos.h>
32592631
GL
52#endif
53
b39dbf34 54#if defined(__GNUWIN32__)
b568d04f
VZ
55 #include <sys/unistd.h>
56 #include <sys/stat.h>
57c208c5 57#endif
32592631 58
eccd1992
VZ
59#if !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
60 #ifndef __UNIX__
61 #include <io.h>
62 #endif
32592631 63
eccd1992
VZ
64 #ifndef __GNUWIN32__
65 #include <shellapi.h>
66 #endif
32592631
GL
67#endif
68
69#include <stdio.h>
70#include <stdlib.h>
71#include <string.h>
72#ifndef __WATCOMC__
3f4a0c5b
VZ
73 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
74 #include <errno.h>
75 #endif
32592631
GL
76#endif
77#include <stdarg.h>
78
731dd422
VZ
79#if wxUSE_IPC
80 #include "wx/dde.h" // for WX_DDE hack in wxExecute
81#endif // wxUSE_IPC
5bd3a2da 82
b481194f 83#include "wx/msw/private/hiddenwin.h"
eccd1992 84
ee6c519a
VZ
85// FIXME-VC6: These are not defined in VC6 SDK headers.
86#ifndef BELOW_NORMAL_PRIORITY_CLASS
87 #define BELOW_NORMAL_PRIORITY_CLASS 0x4000
88#endif
89
90#ifndef ABOVE_NORMAL_PRIORITY_CLASS
91 #define ABOVE_NORMAL_PRIORITY_CLASS 0x8000
92#endif
93
b568d04f
VZ
94// ----------------------------------------------------------------------------
95// constants
96// ----------------------------------------------------------------------------
97
cb6827a8
VZ
98// this message is sent when the process we're waiting for terminates
99#define wxWM_PROC_TERMINATED (WM_USER + 10000)
32592631 100
b568d04f
VZ
101// ----------------------------------------------------------------------------
102// this module globals
103// ----------------------------------------------------------------------------
104
105// we need to create a hidden window to receive the process termination
106// notifications and for this we need a (Win) class name for it which we will
107// register the first time it's needed
eccd1992 108static const wxChar *wxMSWEXEC_WNDCLASSNAME = wxT("_wxExecute_Internal_Class");
b568d04f
VZ
109static const wxChar *gs_classForHiddenWindow = NULL;
110
5a8561fc
VZ
111// event used to wake up threads waiting in wxExecuteThread
112static HANDLE gs_heventShutdown = NULL;
113
114// handles of all threads monitoring the execution of asynchronously running
115// processes
116static wxVector<HANDLE> gs_asyncThreads;
117
b568d04f
VZ
118// ----------------------------------------------------------------------------
119// private types
120// ----------------------------------------------------------------------------
121
cb6827a8
VZ
122// structure describing the process we're being waiting for
123struct wxExecuteData
124{
125public:
126 ~wxExecuteData()
127 {
128 if ( !::CloseHandle(hProcess) )
129 {
f6bcfd97 130 wxLogLastError(wxT("CloseHandle(hProcess)"));
cb6827a8
VZ
131 }
132 }
133
134 HWND hWnd; // window to send wxWM_PROC_TERMINATED to
135 HANDLE hProcess; // handle of the process
136 DWORD dwProcessId; // pid of the process
137 wxProcess *handler;
138 DWORD dwExitCode; // the exit code of the process
27d2dbbc 139 bool state; // set to false when the process finishes
32592631
GL
140};
141
eccd1992
VZ
142class wxExecuteModule : public wxModule
143{
144public:
145 virtual bool OnInit() { return true; }
146 virtual void OnExit()
147 {
5a8561fc
VZ
148 if ( gs_heventShutdown )
149 {
150 // stop any threads waiting for the termination of asynchronously
151 // running processes
152 if ( !::SetEvent(gs_heventShutdown) )
153 {
9a83f860 154 wxLogDebug(wxT("Failed to set shutdown event in wxExecuteModule"));
5a8561fc
VZ
155 }
156
157 ::CloseHandle(gs_heventShutdown);
158 gs_heventShutdown = NULL;
159
160 // now wait until they terminate
161 if ( !gs_asyncThreads.empty() )
162 {
163 const size_t numThreads = gs_asyncThreads.size();
164
165 if ( ::WaitForMultipleObjects
166 (
167 numThreads,
168 &gs_asyncThreads[0],
169 TRUE, // wait for all of them to become signalled
170 3000 // long but finite value
171 ) == WAIT_TIMEOUT )
172 {
9a83f860 173 wxLogDebug(wxT("Failed to stop all wxExecute monitor threads"));
5a8561fc
VZ
174 }
175
176 for ( size_t n = 0; n < numThreads; n++ )
177 {
178 ::CloseHandle(gs_asyncThreads[n]);
179 }
180
181 gs_asyncThreads.clear();
182 }
183 }
184
9978ac8e 185 if ( gs_classForHiddenWindow )
eccd1992
VZ
186 {
187 if ( !::UnregisterClass(wxMSWEXEC_WNDCLASSNAME, wxGetInstance()) )
188 {
9a83f860 189 wxLogLastError(wxT("UnregisterClass(wxExecClass)"));
eccd1992
VZ
190 }
191
192 gs_classForHiddenWindow = NULL;
193 }
194 }
195
196private:
197 DECLARE_DYNAMIC_CLASS(wxExecuteModule)
198};
199
5a8561fc
VZ
200IMPLEMENT_DYNAMIC_CLASS(wxExecuteModule, wxModule)
201
eccd1992 202#if wxUSE_STREAMS && !defined(__WXWINCE__)
8b33ae2d 203
8b33ae2d
GL
204// ----------------------------------------------------------------------------
205// wxPipeStreams
206// ----------------------------------------------------------------------------
207
f6bcfd97
BP
208class wxPipeInputStream: public wxInputStream
209{
8b33ae2d
GL
210public:
211 wxPipeInputStream(HANDLE hInput);
79066131 212 virtual ~wxPipeInputStream();
8b33ae2d 213
27d2dbbc 214 // returns true if the pipe is still opened
79066131
VZ
215 bool IsOpened() const { return m_hInput != INVALID_HANDLE_VALUE; }
216
27d2dbbc 217 // returns true if there is any data to be read from the pipe
2b5f62a0 218 virtual bool CanRead() const;
f6bcfd97 219
8b33ae2d
GL
220protected:
221 size_t OnSysRead(void *buffer, size_t len);
222
223protected:
224 HANDLE m_hInput;
22f3361e 225
c0c133e1 226 wxDECLARE_NO_COPY_CLASS(wxPipeInputStream);
8b33ae2d
GL
227};
228
f6bcfd97
BP
229class wxPipeOutputStream: public wxOutputStream
230{
8b33ae2d
GL
231public:
232 wxPipeOutputStream(HANDLE hOutput);
8f0ff178
RN
233 virtual ~wxPipeOutputStream() { Close(); }
234 bool Close();
8b33ae2d
GL
235
236protected:
237 size_t OnSysWrite(const void *buffer, size_t len);
238
239protected:
240 HANDLE m_hOutput;
22f3361e 241
c0c133e1 242 wxDECLARE_NO_COPY_CLASS(wxPipeOutputStream);
8b33ae2d
GL
243};
244
79066131
VZ
245// define this to let wxexec.cpp know that we know what we're doing
246#define _WX_USED_BY_WXEXECUTE_
247#include "../common/execcmn.cpp"
248
249// ----------------------------------------------------------------------------
250// wxPipe represents a Win32 anonymous pipe
251// ----------------------------------------------------------------------------
252
253class wxPipe
254{
255public:
256 // the symbolic names for the pipe ends
257 enum Direction
258 {
259 Read,
260 Write
261 };
262
263 // default ctor doesn't do anything
264 wxPipe() { m_handles[Read] = m_handles[Write] = INVALID_HANDLE_VALUE; }
265
27d2dbbc 266 // create the pipe, return true if ok, false on error
79066131
VZ
267 bool Create()
268 {
269 // default secutiry attributes
270 SECURITY_ATTRIBUTES security;
271
272 security.nLength = sizeof(security);
273 security.lpSecurityDescriptor = NULL;
274 security.bInheritHandle = TRUE; // to pass it to the child
275
276 if ( !::CreatePipe(&m_handles[0], &m_handles[1], &security, 0) )
277 {
278 wxLogSysError(_("Failed to create an anonymous pipe"));
279
27d2dbbc 280 return false;
79066131
VZ
281 }
282
27d2dbbc 283 return true;
79066131
VZ
284 }
285
27d2dbbc 286 // return true if we were created successfully
79066131
VZ
287 bool IsOk() const { return m_handles[Read] != INVALID_HANDLE_VALUE; }
288
289 // return the descriptor for one of the pipe ends
82baa5e4 290 HANDLE operator[](Direction which) const { return m_handles[which]; }
79066131
VZ
291
292 // detach a descriptor, meaning that the pipe dtor won't close it, and
293 // return it
294 HANDLE Detach(Direction which)
295 {
79066131
VZ
296 HANDLE handle = m_handles[which];
297 m_handles[which] = INVALID_HANDLE_VALUE;
298
299 return handle;
300 }
301
302 // close the pipe descriptors
303 void Close()
304 {
305 for ( size_t n = 0; n < WXSIZEOF(m_handles); n++ )
306 {
307 if ( m_handles[n] != INVALID_HANDLE_VALUE )
308 {
309 ::CloseHandle(m_handles[n]);
310 m_handles[n] = INVALID_HANDLE_VALUE;
311 }
312 }
313 }
314
315 // dtor closes the pipe descriptors
316 ~wxPipe() { Close(); }
317
318private:
319 HANDLE m_handles[2];
320};
321
322#endif // wxUSE_STREAMS
323
324// ============================================================================
325// implementation
326// ============================================================================
327
79066131
VZ
328// ----------------------------------------------------------------------------
329// process termination detecting support
330// ----------------------------------------------------------------------------
331
332// thread function for the thread monitoring the process termination
333static DWORD __stdcall wxExecuteThread(void *arg)
334{
45d5a0c6 335 wxExecuteData * const data = (wxExecuteData *)arg;
79066131 336
5a8561fc
VZ
337 // create the shutdown event if we're the first thread starting to wait
338 if ( !gs_heventShutdown )
79066131 339 {
5a8561fc
VZ
340 // create a manual initially non-signalled event object
341 gs_heventShutdown = ::CreateEvent(NULL, TRUE, FALSE, NULL);
342 if ( !gs_heventShutdown )
343 {
9a83f860 344 wxLogDebug(wxT("CreateEvent() in wxExecuteThread failed"));
5a8561fc 345 }
79066131
VZ
346 }
347
5a8561fc
VZ
348 HANDLE handles[2] = { data->hProcess, gs_heventShutdown };
349 switch ( ::WaitForMultipleObjects(2, handles, FALSE, INFINITE) )
79066131 350 {
5a8561fc
VZ
351 case WAIT_OBJECT_0:
352 // process terminated, get its exit code
353 if ( !::GetExitCodeProcess(data->hProcess, &data->dwExitCode) )
354 {
355 wxLogLastError(wxT("GetExitCodeProcess"));
356 }
357
358 wxASSERT_MSG( data->dwExitCode != STILL_ACTIVE,
359 wxT("process should have terminated") );
79066131 360
5a8561fc
VZ
361 // send a message indicating process termination to the window
362 ::SendMessage(data->hWnd, wxWM_PROC_TERMINATED, 0, (LPARAM)data);
363 break;
364
365 case WAIT_OBJECT_0 + 1:
366 // we're shutting down but the process is still running -- leave it
367 // run but clean up the associated data
368 if ( !data->state )
369 {
370 delete data;
371 }
372 //else: exiting while synchronously executing process is still
373 // running? this shouldn't happen...
374 break;
79066131 375
5a8561fc 376 default:
9a83f860 377 wxLogDebug(wxT("Waiting for the process termination failed!"));
5a8561fc 378 }
79066131
VZ
379
380 return 0;
381}
382
383// window procedure of a hidden window which is created just to receive
384// the notification message when a process exits
385LRESULT APIENTRY _EXPORT wxExecuteWindowCbk(HWND hWnd, UINT message,
386 WPARAM wParam, LPARAM lParam)
387{
388 if ( message == wxWM_PROC_TERMINATED )
389 {
390 DestroyWindow(hWnd); // we don't need it any more
391
45d5a0c6 392 wxExecuteData * const data = (wxExecuteData *)lParam;
79066131
VZ
393 if ( data->handler )
394 {
395 data->handler->OnTerminate((int)data->dwProcessId,
396 (int)data->dwExitCode);
397 }
398
399 if ( data->state )
400 {
401 // we're executing synchronously, tell the waiting thread
402 // that the process finished
5a8561fc 403 data->state = false;
79066131
VZ
404 }
405 else
406 {
407 // asynchronous execution - we should do the clean up
408 delete data;
409 }
410
411 return 0;
412 }
413 else
414 {
45d5a0c6 415 return ::DefWindowProc(hWnd, message, wParam, lParam);
79066131
VZ
416 }
417}
418
419// ============================================================================
420// implementation of IO redirection support classes
421// ============================================================================
422
4676948b 423#if wxUSE_STREAMS && !defined(__WXWINCE__)
79066131
VZ
424
425// ----------------------------------------------------------------------------
426// wxPipeInputStreams
427// ----------------------------------------------------------------------------
8b33ae2d
GL
428
429wxPipeInputStream::wxPipeInputStream(HANDLE hInput)
430{
431 m_hInput = hInput;
cd6ce4a9 432}
8b33ae2d
GL
433
434wxPipeInputStream::~wxPipeInputStream()
435{
79066131
VZ
436 if ( m_hInput != INVALID_HANDLE_VALUE )
437 ::CloseHandle(m_hInput);
8b33ae2d
GL
438}
439
2b5f62a0 440bool wxPipeInputStream::CanRead() const
8b33ae2d 441{
386a2898
VZ
442 // we can read if there's something in the put back buffer
443 // even pipe is closed
444 if ( m_wbacksize > m_wbackcur )
445 return true;
446
447 wxPipeInputStream * const self = wxConstCast(this, wxPipeInputStream);
448
79066131 449 if ( !IsOpened() )
386a2898
VZ
450 {
451 // set back to mark Eof as it may have been unset by Ungetch()
452 self->m_lasterror = wxSTREAM_EOF;
27d2dbbc 453 return false;
386a2898 454 }
79066131 455
f6bcfd97
BP
456 DWORD nAvailable;
457
458 // function name is misleading, it works with anon pipes as well
459 DWORD rc = ::PeekNamedPipe
460 (
461 m_hInput, // handle
462 NULL, 0, // ptr to buffer and its size
463 NULL, // [out] bytes read
464 &nAvailable, // [out] bytes available
465 NULL // [out] bytes left
466 );
467
468 if ( !rc )
469 {
470 if ( ::GetLastError() != ERROR_BROKEN_PIPE )
471 {
472 // unexpected error
9a83f860 473 wxLogLastError(wxT("PeekNamedPipe"));
f6bcfd97 474 }
8b33ae2d 475
3103e8a9 476 // don't try to continue reading from a pipe if an error occurred or if
f6bcfd97 477 // it had been closed
79066131
VZ
478 ::CloseHandle(m_hInput);
479
2b5f62a0
VZ
480 self->m_hInput = INVALID_HANDLE_VALUE;
481 self->m_lasterror = wxSTREAM_EOF;
482
483 nAvailable = 0;
f6bcfd97 484 }
79066131
VZ
485
486 return nAvailable != 0;
f6bcfd97
BP
487}
488
489size_t wxPipeInputStream::OnSysRead(void *buffer, size_t len)
490{
2b5f62a0 491 if ( !IsOpened() )
79066131
VZ
492 {
493 m_lasterror = wxSTREAM_EOF;
494
f6bcfd97 495 return 0;
79066131
VZ
496 }
497
f6bcfd97
BP
498 DWORD bytesRead;
499 if ( !::ReadFile(m_hInput, buffer, len, &bytesRead, NULL) )
500 {
2b5f62a0
VZ
501 m_lasterror = ::GetLastError() == ERROR_BROKEN_PIPE
502 ? wxSTREAM_EOF
503 : wxSTREAM_READ_ERROR;
8b33ae2d 504 }
f6bcfd97 505
3103e8a9 506 // bytesRead is set to 0, as desired, if an error occurred
8b33ae2d
GL
507 return bytesRead;
508}
509
79066131 510// ----------------------------------------------------------------------------
8b33ae2d 511// wxPipeOutputStream
79066131 512// ----------------------------------------------------------------------------
8b33ae2d
GL
513
514wxPipeOutputStream::wxPipeOutputStream(HANDLE hOutput)
515{
516 m_hOutput = hOutput;
3338a5bd
VZ
517
518 // unblock the pipe to prevent deadlocks when we're writing to the pipe
519 // from which the child process can't read because it is writing in its own
520 // end of it
521 DWORD mode = PIPE_READMODE_BYTE | PIPE_NOWAIT;
522 if ( !::SetNamedPipeHandleState
523 (
524 m_hOutput,
525 &mode,
526 NULL, // collection count (we don't set it)
527 NULL // timeout (we don't set it neither)
528 ) )
529 {
9a83f860 530 wxLogLastError(wxT("SetNamedPipeHandleState(PIPE_NOWAIT)"));
3338a5bd 531 }
cd6ce4a9 532}
8b33ae2d 533
8f0ff178 534bool wxPipeOutputStream::Close()
8b33ae2d 535{
8f0ff178 536 return ::CloseHandle(m_hOutput) != 0;
8b33ae2d
GL
537}
538
8f0ff178 539
8b33ae2d
GL
540size_t wxPipeOutputStream::OnSysWrite(const void *buffer, size_t len)
541{
2b5f62a0 542 m_lasterror = wxSTREAM_NO_ERROR;
3338a5bd
VZ
543
544 DWORD totalWritten = 0;
545 while ( len > 0 )
f6bcfd97 546 {
3338a5bd
VZ
547 DWORD chunkWritten;
548 if ( !::WriteFile(m_hOutput, buffer, len, &chunkWritten, NULL) )
549 {
550 m_lasterror = ::GetLastError() == ERROR_BROKEN_PIPE
551 ? wxSTREAM_EOF
552 : wxSTREAM_WRITE_ERROR;
553 break;
554 }
555
556 if ( !chunkWritten )
557 break;
558
559 buffer = (char *)buffer + chunkWritten;
560 totalWritten += chunkWritten;
561 len -= chunkWritten;
8b33ae2d 562 }
f6bcfd97 563
3338a5bd 564 return totalWritten;
8b33ae2d
GL
565}
566
79066131
VZ
567#endif // wxUSE_STREAMS
568
b568d04f 569// ============================================================================
79066131 570// wxExecute functions family
b568d04f 571// ============================================================================
5260b1c5 572
ca289436
VZ
573#if wxUSE_IPC
574
575// connect to the given server via DDE and ask it to execute the command
42d0df00
VZ
576bool
577wxExecuteDDE(const wxString& ddeServer,
578 const wxString& ddeTopic,
579 const wxString& ddeCommand)
ca289436 580{
999836aa 581 bool ok wxDUMMY_INITIALIZE(false);
ca289436
VZ
582
583 wxDDEClient client;
42d0df00
VZ
584 wxConnectionBase *
585 conn = client.MakeConnection(wxEmptyString, ddeServer, ddeTopic);
ca289436
VZ
586 if ( !conn )
587 {
27d2dbbc 588 ok = false;
ca289436
VZ
589 }
590 else // connected to DDE server
591 {
4dd03db9
VZ
592 // the added complication here is that although most programs use
593 // XTYP_EXECUTE for their DDE API, some important ones -- like Word
594 // and other MS stuff - use XTYP_REQUEST!
ca289436 595 //
4dd03db9
VZ
596 // moreover, anotheri mportant program (IE) understands both but
597 // returns an error from Execute() so we must try Request() first
598 // to avoid doing it twice
ca289436 599 {
4dd03db9 600 // we're prepared for this one to fail, so don't show errors
ca289436 601 wxLogNull noErrors;
4dd03db9
VZ
602
603 ok = conn->Request(ddeCommand) != NULL;
ca289436
VZ
604 }
605
606 if ( !ok )
607 {
4dd03db9
VZ
608 // now try execute -- but show the errors
609 ok = conn->Execute(ddeCommand);
ca289436
VZ
610 }
611 }
612
613 return ok;
614}
615
616#endif // wxUSE_IPC
617
164db92c
VZ
618long wxExecute(const wxString& cmd, int flags, wxProcess *handler,
619 const wxExecuteEnv *env)
32592631 620{
c3fad64b 621 wxCHECK_MSG( !cmd.empty(), 0, wxT("empty command in wxExecute") );
5bd3a2da 622
647b8e37
VZ
623#if wxUSE_THREADS
624 // for many reasons, the code below breaks down if it's called from another
625 // thread -- this could be fixed, but as Unix versions don't support this
626 // neither I don't want to waste time on this now
627 wxASSERT_MSG( wxThread::IsMain(),
9a83f860 628 wxT("wxExecute() can be called only from the main thread") );
647b8e37
VZ
629#endif // wxUSE_THREADS
630
039f62f4 631 wxString command;
6ba63600 632
731dd422 633#if wxUSE_IPC
5bd3a2da
VZ
634 // DDE hack: this is really not pretty, but we need to allow this for
635 // transparent handling of DDE servers in wxMimeTypesManager. Usually it
636 // returns the command which should be run to view/open/... a file of the
637 // given type. Sometimes, however, this command just launches the server
638 // and an additional DDE request must be made to really open the file. To
639 // keep all this well hidden from the application, we allow a special form
6ba63600 640 // of command: WX_DDE#<command>#DDE_SERVER#DDE_TOPIC#DDE_COMMAND in which
5bd3a2da 641 // case we execute just <command> and process the rest below
039f62f4 642 wxString ddeServer, ddeTopic, ddeCommand;
5bd3a2da 643 static const size_t lenDdePrefix = 7; // strlen("WX_DDE:")
9a83f860 644 if ( cmd.Left(lenDdePrefix) == wxT("WX_DDE#") )
5bd3a2da 645 {
ca289436
VZ
646 // speed up the concatenations below
647 ddeServer.reserve(256);
648 ddeTopic.reserve(256);
649 ddeCommand.reserve(256);
650
5bd3a2da 651 const wxChar *p = cmd.c_str() + 7;
9a83f860 652 while ( *p && *p != wxT('#') )
5bd3a2da
VZ
653 {
654 command += *p++;
655 }
656
657 if ( *p )
658 {
659 // skip '#'
660 p++;
661 }
662 else
663 {
9a83f860 664 wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute"));
5bd3a2da
VZ
665 }
666
9a83f860 667 while ( *p && *p != wxT('#') )
5bd3a2da
VZ
668 {
669 ddeServer += *p++;
670 }
671
672 if ( *p )
673 {
674 // skip '#'
675 p++;
676 }
677 else
678 {
9a83f860 679 wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute"));
5bd3a2da
VZ
680 }
681
9a83f860 682 while ( *p && *p != wxT('#') )
5bd3a2da
VZ
683 {
684 ddeTopic += *p++;
685 }
686
687 if ( *p )
688 {
689 // skip '#'
690 p++;
691 }
692 else
693 {
9a83f860 694 wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute"));
5bd3a2da
VZ
695 }
696
697 while ( *p )
698 {
699 ddeCommand += *p++;
700 }
6ba63600 701
ca289436
VZ
702 // if we want to just launch the program and not wait for its
703 // termination, try to execute DDE command right now, it can succeed if
704 // the process is already running - but as it fails if it's not
705 // running, suppress any errors it might generate
fbf456aa 706 if ( !(flags & wxEXEC_SYNC) )
6ba63600 707 {
ca289436
VZ
708 wxLogNull noErrors;
709 if ( wxExecuteDDE(ddeServer, ddeTopic, ddeCommand) )
710 {
711 // a dummy PID - this is a hack, of course, but it's well worth
712 // it as we don't open a new server each time we're called
713 // which would be quite bad
714 return -1;
715 }
6ba63600 716 }
5bd3a2da
VZ
717 }
718 else
731dd422 719#endif // wxUSE_IPC
5bd3a2da
VZ
720 {
721 // no DDE
722 command = cmd;
723 }
32592631 724
f6bcfd97
BP
725 // the IO redirection is only supported with wxUSE_STREAMS
726 BOOL redirect = FALSE;
79066131 727
4676948b 728#if wxUSE_STREAMS && !defined(__WXWINCE__)
79066131
VZ
729 wxPipe pipeIn, pipeOut, pipeErr;
730
731 // we'll save here the copy of pipeIn[Write]
33ac7e6f 732 HANDLE hpipeStdinWrite = INVALID_HANDLE_VALUE;
8b33ae2d 733
cd6ce4a9 734 // open the pipes to which child process IO will be redirected if needed
cd6ce4a9
VZ
735 if ( handler && handler->IsRedirected() )
736 {
79066131
VZ
737 // create pipes for redirecting stdin, stdout and stderr
738 if ( !pipeIn.Create() || !pipeOut.Create() || !pipeErr.Create() )
cd6ce4a9 739 {
79066131 740 wxLogSysError(_("Failed to redirect the child process IO"));
8b33ae2d 741
fbf456aa
VZ
742 // indicate failure: we need to return different error code
743 // depending on the sync flag
744 return flags & wxEXEC_SYNC ? -1 : 0;
8b33ae2d
GL
745 }
746
f6bcfd97 747 redirect = TRUE;
8b33ae2d 748 }
f6bcfd97 749#endif // wxUSE_STREAMS
5bd3a2da 750
cb6827a8
VZ
751 // create the process
752 STARTUPINFO si;
11c7d5b6 753 wxZeroMemory(si);
cb6827a8
VZ
754 si.cb = sizeof(si);
755
4676948b 756#if wxUSE_STREAMS && !defined(__WXWINCE__)
f6bcfd97 757 if ( redirect )
cb6827a8 758 {
fbf456aa 759 si.dwFlags = STARTF_USESTDHANDLES;
f6bcfd97 760
79066131
VZ
761 si.hStdInput = pipeIn[wxPipe::Read];
762 si.hStdOutput = pipeOut[wxPipe::Write];
763 si.hStdError = pipeErr[wxPipe::Write];
f6bcfd97 764
f6bcfd97 765 // we must duplicate the handle to the write side of stdin pipe to make
79066131
VZ
766 // it non inheritable: indeed, we must close the writing end of pipeIn
767 // before launching the child process as otherwise this handle will be
f6bcfd97
BP
768 // inherited by the child which will never close it and so the pipe
769 // will never be closed and the child will be left stuck in ReadFile()
79066131 770 HANDLE pipeInWrite = pipeIn.Detach(wxPipe::Write);
f6bcfd97
BP
771 if ( !::DuplicateHandle
772 (
79066131
VZ
773 ::GetCurrentProcess(),
774 pipeInWrite,
775 ::GetCurrentProcess(),
f6bcfd97
BP
776 &hpipeStdinWrite,
777 0, // desired access: unused here
778 FALSE, // not inherited
779 DUPLICATE_SAME_ACCESS // same access as for src handle
780 ) )
cd6ce4a9 781 {
9a83f860 782 wxLogLastError(wxT("DuplicateHandle"));
8b33ae2d 783 }
cd6ce4a9 784
79066131 785 ::CloseHandle(pipeInWrite);
f6bcfd97
BP
786 }
787#endif // wxUSE_STREAMS
cb6827a8 788
4fe4a7c5
VZ
789 // The default logic for showing the console is to show it only if the IO
790 // is not redirected however wxEXEC_{SHOW,HIDE}_CONSOLE flags can be
791 // explicitly specified to change it.
792 if ( (flags & wxEXEC_HIDE_CONSOLE) ||
793 (redirect && !(flags & wxEXEC_SHOW_CONSOLE)) )
794 {
795 si.dwFlags |= STARTF_USESHOWWINDOW;
796 si.wShowWindow = SW_HIDE;
797 }
798
799
f6bcfd97 800 PROCESS_INFORMATION pi;
4676948b 801 DWORD dwFlags = CREATE_SUSPENDED;
78c743d8 802
4676948b 803#ifndef __WXWINCE__
ee4d4380
VZ
804 if ( (flags & wxEXEC_MAKE_GROUP_LEADER) &&
805 (wxGetOsVersion() == wxOS_WINDOWS_NT) )
806 dwFlags |= CREATE_NEW_PROCESS_GROUP;
807
4676948b 808 dwFlags |= CREATE_DEFAULT_ERROR_MODE ;
78c743d8 809#else
9cd03a43
WS
810 // we are assuming commands without spaces for now
811 wxString moduleName = command.BeforeFirst(wxT(' '));
812 wxString arguments = command.AfterFirst(wxT(' '));
4676948b 813#endif
f6bcfd97 814
164db92c
VZ
815 wxWxCharBuffer envBuffer;
816 bool useCwd = false;
817 if ( env )
818 {
819 useCwd = !env->cwd.empty();
820
821 // Translate environment variable map into NUL-terminated list of
822 // NUL-terminated strings.
823 if ( !env->env.empty() )
824 {
825#if wxUSE_UNICODE
826 // Environment variables can contain non-ASCII characters. We could
827 // check for it and not use this flag if everything is really ASCII
828 // only but there doesn't seem to be any reason to do it so just
829 // assume Unicode by default.
830 dwFlags |= CREATE_UNICODE_ENVIRONMENT;
831#endif // wxUSE_UNICODE
832
833 wxEnvVariableHashMap::const_iterator it;
834
835 size_t envSz = 1; // ending '\0'
836 for ( it = env->env.begin(); it != env->env.end(); ++it )
837 {
838 // Add size of env variable name and value, and '=' char and
839 // ending '\0'
840 envSz += it->first.length() + it->second.length() + 2;
841 }
842
843 envBuffer.extend(envSz);
844
845 wxChar *p = envBuffer.data();
846 for ( it = env->env.begin(); it != env->env.end(); ++it )
847 {
848 const wxString line = it->first + wxS("=") + it->second;
849
850 // Include the trailing NUL which will always terminate the
851 // buffer returned by t_str().
852 const size_t len = line.length() + 1;
853
854 wxTmemcpy(p, line.t_str(), len);
855
856 p += len;
857 }
858
859 // And another NUL to terminate the list of NUL-terminated strings.
860 *p = 0;
861 }
862 }
863
eaf4bde6 864 // Translate wxWidgets priority to Windows conventions.
b640fa17 865 if ( handler )
eaf4bde6 866 {
b640fa17
VZ
867 unsigned prio = handler->GetPriority();
868 if ( prio <= 20 )
869 dwFlags |= IDLE_PRIORITY_CLASS;
870 else if ( prio <= 40 )
871 dwFlags |= BELOW_NORMAL_PRIORITY_CLASS;
872 else if ( prio <= 60 )
873 dwFlags |= NORMAL_PRIORITY_CLASS;
874 else if ( prio <= 80 )
875 dwFlags |= ABOVE_NORMAL_PRIORITY_CLASS;
876 else if ( prio <= 99 )
877 dwFlags |= HIGH_PRIORITY_CLASS;
878 else if ( prio <= 100 )
879 dwFlags |= REALTIME_PRIORITY_CLASS;
880 else
881 {
882 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
883 dwFlags |= NORMAL_PRIORITY_CLASS;
884 }
eaf4bde6
VZ
885 }
886
f6bcfd97
BP
887 bool ok = ::CreateProcess
888 (
9cd03a43 889 // WinCE requires appname to be non null
78c743d8
JS
890 // Win32 allows for null
891#ifdef __WXWINCE__
125afca0
VZ
892 moduleName.t_str(), // application name
893 wxMSW_CONV_LPTSTR(arguments), // arguments
78c743d8 894#else
9cd03a43 895 NULL, // application name (use only cmd line)
125afca0 896 wxMSW_CONV_LPTSTR(command), // full command line
78c743d8 897#endif
9cd03a43
WS
898 NULL, // security attributes: defaults for both
899 NULL, // the process and its main thread
900 redirect, // inherit handles if we use pipes
901 dwFlags, // process creation flags
164db92c
VZ
902 envBuffer.data(), // environment (may be NULL which is fine)
903 useCwd // initial working directory
125afca0 904 ? wxMSW_CONV_LPTSTR(env->cwd)
164db92c 905 : NULL, // (or use the same)
9cd03a43
WS
906 &si, // startup info (unused here)
907 &pi // process info
f6bcfd97
BP
908 ) != 0;
909
4676948b 910#if wxUSE_STREAMS && !defined(__WXWINCE__)
f6bcfd97
BP
911 // we can close the pipe ends used by child anyhow
912 if ( redirect )
913 {
79066131
VZ
914 ::CloseHandle(pipeIn.Detach(wxPipe::Read));
915 ::CloseHandle(pipeOut.Detach(wxPipe::Write));
916 ::CloseHandle(pipeErr.Detach(wxPipe::Write));
cb6827a8 917 }
f6bcfd97 918#endif // wxUSE_STREAMS
cb6827a8 919
f6bcfd97 920 if ( !ok )
5e1febfa 921 {
4676948b 922#if wxUSE_STREAMS && !defined(__WXWINCE__)
f6bcfd97
BP
923 // close the other handles too
924 if ( redirect )
5e1febfa 925 {
79066131
VZ
926 ::CloseHandle(pipeOut.Detach(wxPipe::Read));
927 ::CloseHandle(pipeErr.Detach(wxPipe::Read));
5e1febfa 928 }
f6bcfd97 929#endif // wxUSE_STREAMS
5e1febfa 930
f6bcfd97
BP
931 wxLogSysError(_("Execution of command '%s' failed"), command.c_str());
932
fbf456aa 933 return flags & wxEXEC_SYNC ? -1 : 0;
f6bcfd97 934 }
8b33ae2d 935
4676948b 936#if wxUSE_STREAMS && !defined(__WXWINCE__)
79066131
VZ
937 // the input buffer bufOut is connected to stdout, this is why it is
938 // called bufOut and not bufIn
939 wxStreamTempInputBuffer bufOut,
940 bufErr;
941
f6bcfd97
BP
942 if ( redirect )
943 {
8b33ae2d 944 // We can now initialize the wxStreams
79066131
VZ
945 wxPipeInputStream *
946 outStream = new wxPipeInputStream(pipeOut.Detach(wxPipe::Read));
947 wxPipeInputStream *
948 errStream = new wxPipeInputStream(pipeErr.Detach(wxPipe::Read));
949 wxPipeOutputStream *
950 inStream = new wxPipeOutputStream(hpipeStdinWrite);
951
952 handler->SetPipeStreams(outStream, inStream, errStream);
8b33ae2d 953
79066131
VZ
954 bufOut.Init(outStream);
955 bufErr.Init(errStream);
8b33ae2d 956 }
f6bcfd97 957#endif // wxUSE_STREAMS
8b33ae2d 958
cb6827a8
VZ
959 // create a hidden window to receive notification about process
960 // termination
eccd1992
VZ
961 HWND hwnd = wxCreateHiddenWindow
962 (
963 &gs_classForHiddenWindow,
964 wxMSWEXEC_WNDCLASSNAME,
965 (WNDPROC)wxExecuteWindowCbk
966 );
967
223d09f6 968 wxASSERT_MSG( hwnd, wxT("can't create a hidden window for wxExecute") );
e6045e08 969
cb6827a8
VZ
970 // Alloc data
971 wxExecuteData *data = new wxExecuteData;
972 data->hProcess = pi.hProcess;
973 data->dwProcessId = pi.dwProcessId;
974 data->hWnd = hwnd;
fbf456aa
VZ
975 data->state = (flags & wxEXEC_SYNC) != 0;
976 if ( flags & wxEXEC_SYNC )
e6045e08 977 {
5e1febfa
VZ
978 // handler may be !NULL for capturing program output, but we don't use
979 // it wxExecuteData struct in this case
e6045e08
VZ
980 data->handler = NULL;
981 }
982 else
983 {
984 // may be NULL or not
985 data->handler = handler;
ca5016d4
FM
986
987 if (handler)
988 handler->SetPid(pi.dwProcessId);
e6045e08 989 }
cb6827a8
VZ
990
991 DWORD tid;
992 HANDLE hThread = ::CreateThread(NULL,
993 0,
19193a2c 994 wxExecuteThread,
cb6827a8
VZ
995 (void *)data,
996 0,
997 &tid);
998
0d7ea902
VZ
999 // resume process we created now - whether the thread creation succeeded or
1000 // not
1001 if ( ::ResumeThread(pi.hThread) == (DWORD)-1 )
1002 {
1003 // ignore it - what can we do?
f6bcfd97 1004 wxLogLastError(wxT("ResumeThread in wxExecute"));
0d7ea902
VZ
1005 }
1006
1007 // close unneeded handle
1008 if ( !::CloseHandle(pi.hThread) )
43b2d5e7 1009 {
f6bcfd97 1010 wxLogLastError(wxT("CloseHandle(hThread)"));
43b2d5e7 1011 }
0d7ea902 1012
cb6827a8
VZ
1013 if ( !hThread )
1014 {
f6bcfd97 1015 wxLogLastError(wxT("CreateThread in wxExecute"));
cb6827a8
VZ
1016
1017 DestroyWindow(hwnd);
1018 delete data;
1019
1020 // the process still started up successfully...
1021 return pi.dwProcessId;
1022 }
e6045e08 1023
5a8561fc 1024 gs_asyncThreads.push_back(hThread);
f6bcfd97 1025
4676948b 1026#if wxUSE_IPC && !defined(__WXWINCE__)
5bd3a2da
VZ
1027 // second part of DDE hack: now establish the DDE conversation with the
1028 // just launched process
ca289436 1029 if ( !ddeServer.empty() )
5bd3a2da 1030 {
daa35097 1031 bool ddeOK;
ca289436
VZ
1032
1033 // give the process the time to init itself
1034 //
1035 // we use a very big timeout hoping that WaitForInputIdle() will return
1036 // much sooner, but not INFINITE just in case the process hangs
1037 // completely - like this we will regain control sooner or later
1038 switch ( ::WaitForInputIdle(pi.hProcess, 10000 /* 10 seconds */) )
6ba63600 1039 {
ca289436 1040 default:
9a83f860 1041 wxFAIL_MSG( wxT("unexpected WaitForInputIdle() return code") );
ca289436 1042 // fall through
6ba63600 1043
53d7ab95 1044 case WAIT_FAILED:
9a83f860 1045 wxLogLastError(wxT("WaitForInputIdle() in wxExecute"));
6ba63600 1046
ca289436 1047 case WAIT_TIMEOUT:
9a83f860 1048 wxLogDebug(wxT("Timeout too small in WaitForInputIdle"));
ca289436 1049
daa35097 1050 ddeOK = false;
ca289436
VZ
1051 break;
1052
1053 case 0:
1054 // ok, process ready to accept DDE requests
daa35097 1055 ddeOK = wxExecuteDDE(ddeServer, ddeTopic, ddeCommand);
6ba63600 1056 }
1b47bebc 1057
daa35097 1058 if ( !ddeOK )
1b47bebc 1059 {
9a83f860 1060 wxLogDebug(wxT("Failed to send DDE request to the process \"%s\"."),
1b47bebc
VZ
1061 cmd.c_str());
1062 }
5bd3a2da 1063 }
731dd422 1064#endif // wxUSE_IPC
5bd3a2da 1065
fbf456aa 1066 if ( !(flags & wxEXEC_SYNC) )
cb6827a8
VZ
1067 {
1068 // clean up will be done when the process terminates
e6045e08
VZ
1069
1070 // return the pid
cb6827a8
VZ
1071 return pi.dwProcessId;
1072 }
e6045e08 1073
d60e2332 1074 wxAppTraits *traits = wxTheApp ? wxTheApp->GetTraits() : NULL;
9a83f860 1075 wxCHECK_MSG( traits, -1, wxT("no wxAppTraits in wxExecute()?") );
d60e2332 1076
c3fad64b 1077 void *cookie = NULL;
f38f6899
VZ
1078 if ( !(flags & wxEXEC_NODISABLE) )
1079 {
f38f6899
VZ
1080 // disable all app windows while waiting for the child process to finish
1081 cookie = traits->BeforeChildWaitLoop();
1082 }
e2478fde
VZ
1083
1084 // wait until the child process terminates
1085 while ( data->state )
1086 {
4676948b 1087#if wxUSE_STREAMS && !defined(__WXWINCE__)
4d425dee 1088 if ( !bufOut.Update() && !bufErr.Update() )
79066131 1089#endif // wxUSE_STREAMS
4d425dee
VZ
1090 {
1091 // don't eat 100% of the CPU -- ugly but anything else requires
1092 // real async IO which we don't have for the moment
1093 ::Sleep(50);
1094 }
e6045e08 1095
dbbcfbb6
VZ
1096 // we must always process messages for our hidden window or we'd never
1097 // get wxWM_PROC_TERMINATED and so this loop would never terminate
1098 MSG msg;
1099 ::PeekMessage(&msg, data->hWnd, 0, 0, PM_REMOVE);
1100
1101 // we may also need to process messages for all the other application
1102 // windows
1103 if ( !(flags & wxEXEC_NOEVENTS) )
1104 {
1105 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
1106 if ( loop )
1107 loop->Yield();
1108 }
cd6ce4a9 1109 }
068a7cfe 1110
d60e2332
VZ
1111 if ( !(flags & wxEXEC_NODISABLE) )
1112 {
1113 // reenable disabled windows back
f38f6899 1114 traits->AfterChildWaitLoop(cookie);
d60e2332 1115 }
0d7ea902 1116
e6045e08 1117 DWORD dwExitCode = data->dwExitCode;
cb6827a8
VZ
1118 delete data;
1119
e6045e08
VZ
1120 // return the exit code
1121 return dwExitCode;
32592631 1122}
c740f496 1123
05718a98 1124template <typename CharType>
164db92c
VZ
1125long wxExecuteImpl(CharType **argv, int flags, wxProcess *handler,
1126 const wxExecuteEnv *env)
c740f496 1127{
cb6827a8 1128 wxString command;
05718a98 1129 command.reserve(1024);
e6045e08 1130
3cdd564f 1131 wxString arg;
0493ba13 1132 for ( ;; )
cb6827a8 1133 {
3cdd564f
VZ
1134 arg = *argv++;
1135
a6eac99d
VZ
1136 bool quote;
1137 if ( arg.empty() )
1138 {
1139 // we need to quote empty arguments, otherwise they'd just
1140 // disappear
1141 quote = true;
1142 }
1143 else // non-empty
1144 {
1145 // escape any quotes present in the string to avoid interfering
1146 // with the command line parsing in the child process
1147 arg.Replace("\"", "\\\"", true /* replace all */);
3cdd564f 1148
a6eac99d
VZ
1149 // and quote any arguments containing the spaces to prevent them from
1150 // being broken down
1151 quote = arg.find_first_of(" \t") != wxString::npos;
1152 }
1153
1154 if ( quote )
3cdd564f 1155 command += '\"' + arg + '\"';
a6eac99d
VZ
1156 else
1157 command += arg;
3cdd564f 1158
0493ba13
VZ
1159 if ( !*argv )
1160 break;
cb6827a8 1161
05718a98 1162 command += ' ';
0493ba13 1163 }
cb6827a8 1164
164db92c 1165 return wxExecute(command, flags, handler, env);
c740f496 1166}
05718a98 1167
164db92c
VZ
1168long wxExecute(char **argv, int flags, wxProcess *handler,
1169 const wxExecuteEnv *env)
05718a98 1170{
164db92c 1171 return wxExecuteImpl(argv, flags, handler, env);
05718a98
VZ
1172}
1173
d7ef641d
VZ
1174#if wxUSE_UNICODE
1175
164db92c
VZ
1176long wxExecute(wchar_t **argv, int flags, wxProcess *handler,
1177 const wxExecuteEnv *env)
05718a98 1178{
164db92c 1179 return wxExecuteImpl(argv, flags, handler, env);
05718a98 1180}
d7ef641d
VZ
1181
1182#endif // wxUSE_UNICODE