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