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