1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: exec sample demonstrates wxExecute and related functions
4 // Author: Vadim Zeitlin
8 // Copyright: (c) Vadim Zeitlin
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
21 #pragma implementation "exec.cpp"
22 #pragma interface "exec.cpp"
25 // For compilers that support precompilation, includes "wx/wx.h".
26 #include "wx/wxprec.h"
32 // for all others, include the necessary headers (this file is usually all you
33 // need because it includes almost all "standard" wxWindows headers
39 #include "wx/msgdlg.h"
40 #include "wx/textdlg.h"
41 #include "wx/listbox.h"
42 #include "wx/filedlg.h"
43 #include "wx/choicdlg.h"
46 #include "wx/txtstrm.h"
48 #include "wx/process.h"
50 #include "wx/mimetype.h"
56 // ----------------------------------------------------------------------------
58 // ----------------------------------------------------------------------------
60 // Define a new application type, each program should derive a class from wxApp
61 class MyApp
: public wxApp
64 // override base class virtuals
65 // ----------------------------
67 // this one is called on application startup and is a good place for the app
68 // initialization (doing it here and not in the ctor allows to have an error
69 // return: if OnInit() returns false, the application terminates)
70 virtual bool OnInit();
73 // Define an array of process pointers used by MyFrame
75 WX_DEFINE_ARRAY(MyPipedProcess
*, MyProcessesArray
);
77 // Define a new frame type: this is going to be our main frame
78 class MyFrame
: public wxFrame
82 MyFrame(const wxString
& title
, const wxPoint
& pos
, const wxSize
& size
);
84 // event handlers (these functions should _not_ be virtual)
85 void OnQuit(wxCommandEvent
& event
);
87 void OnKill(wxCommandEvent
& event
);
89 void OnClear(wxCommandEvent
& event
);
91 void OnSyncExec(wxCommandEvent
& event
);
92 void OnAsyncExec(wxCommandEvent
& event
);
93 void OnShell(wxCommandEvent
& event
);
94 void OnExecWithRedirect(wxCommandEvent
& event
);
95 void OnExecWithPipe(wxCommandEvent
& event
);
97 void OnFileExec(wxCommandEvent
& event
);
99 void OnAbout(wxCommandEvent
& event
);
101 // polling output of async processes
102 void OnIdle(wxIdleEvent
& event
);
104 // for MyPipedProcess
105 void OnProcessTerminated(MyPipedProcess
*process
);
106 wxListBox
*GetLogListBox() const { return m_lbox
; }
109 void ShowOutput(const wxString
& cmd
,
110 const wxArrayString
& output
,
111 const wxString
& title
);
113 void DoAsyncExec(const wxString
& cmd
);
115 // the PID of the last process we launched asynchronously
118 // last command we executed
122 void OnDDEExec(wxCommandEvent
& event
);
123 void OnDDERequest(wxCommandEvent
& event
);
127 // last params of a DDE transaction
131 #endif // __WINDOWS__
135 MyProcessesArray m_running
;
137 // any class wishing to process wxWindows events must use this macro
138 DECLARE_EVENT_TABLE()
141 // This is the handler for process termination events
142 class MyProcess
: public wxProcess
145 MyProcess(MyFrame
*parent
, const wxString
& cmd
)
146 : wxProcess(parent
), m_cmd(cmd
)
151 // instead of overriding this virtual function we might as well process the
152 // event from it in the frame class - this might be more convenient in some
154 virtual void OnTerminate(int pid
, int status
);
161 // A specialization of MyProcess for redirecting the output
162 class MyPipedProcess
: public MyProcess
165 MyPipedProcess(MyFrame
*parent
, const wxString
& cmd
)
166 : MyProcess(parent
, cmd
)
171 virtual void OnTerminate(int pid
, int status
);
173 virtual bool HasInput();
176 // A version of MyPipedProcess which also sends input to the stdin of the
178 class MyPipedProcess2
: public MyPipedProcess
181 MyPipedProcess2(MyFrame
*parent
, const wxString
& cmd
, const wxString
& input
)
182 : MyPipedProcess(parent
, cmd
), m_input(input
)
186 virtual bool HasInput();
192 // ----------------------------------------------------------------------------
194 // ----------------------------------------------------------------------------
196 // IDs for the controls and the menu commands
214 static const wxChar
*DIALOG_TITLE
= _T("Exec sample");
216 // ----------------------------------------------------------------------------
217 // event tables and other macros for wxWindows
218 // ----------------------------------------------------------------------------
220 // the event tables connect the wxWindows events with the functions (event
221 // handlers) which process them. It can be also done at run-time, but for the
222 // simple menu events like this the static method is much simpler.
223 BEGIN_EVENT_TABLE(MyFrame
, wxFrame
)
224 EVT_MENU(Exec_Quit
, MyFrame::OnQuit
)
225 EVT_MENU(Exec_Kill
, MyFrame::OnKill
)
226 EVT_MENU(Exec_ClearLog
, MyFrame::OnClear
)
228 EVT_MENU(Exec_SyncExec
, MyFrame::OnSyncExec
)
229 EVT_MENU(Exec_AsyncExec
, MyFrame::OnAsyncExec
)
230 EVT_MENU(Exec_Shell
, MyFrame::OnShell
)
231 EVT_MENU(Exec_Redirect
, MyFrame::OnExecWithRedirect
)
232 EVT_MENU(Exec_Pipe
, MyFrame::OnExecWithPipe
)
234 EVT_MENU(Exec_OpenFile
, MyFrame::OnFileExec
)
236 EVT_MENU(Exec_DDEExec
, MyFrame::OnDDEExec
)
237 EVT_MENU(Exec_DDERequest
, MyFrame::OnDDERequest
)
239 EVT_MENU(Exec_About
, MyFrame::OnAbout
)
241 EVT_IDLE(MyFrame::OnIdle
)
244 // Create a new application object: this macro will allow wxWindows to create
245 // the application object during program execution (it's better than using a
246 // static object for many reasons) and also declares the accessor function
247 // wxGetApp() which will return the reference of the right type (i.e. MyApp and
251 // ============================================================================
253 // ============================================================================
255 // ----------------------------------------------------------------------------
256 // the application class
257 // ----------------------------------------------------------------------------
259 // `Main program' equivalent: the program execution "starts" here
262 // Create the main application window
263 MyFrame
*frame
= new MyFrame(_T("Exec wxWindows sample"),
264 wxDefaultPosition
, wxSize(500, 140));
266 // Show it and tell the application that it's our main window
270 // success: wxApp::OnRun() will be called which will enter the main message
271 // loop and the application will run. If we returned FALSE here, the
272 // application would exit immediately.
276 // ----------------------------------------------------------------------------
278 // ----------------------------------------------------------------------------
281 MyFrame::MyFrame(const wxString
& title
, const wxPoint
& pos
, const wxSize
& size
)
282 : wxFrame((wxFrame
*)NULL
, -1, title
, pos
, size
)
287 // we need this in order to allow the about menu relocation, since ABOUT is
288 // not the default id of the about menu
289 wxApp::s_macAboutMenuItemId
= Exec_About
;
293 wxMenu
*menuFile
= new wxMenu(_T(""), wxMENU_TEAROFF
);
294 menuFile
->Append(Exec_Kill
, _T("&Kill process...\tCtrl-K"),
295 _T("Kill a process by PID"));
296 menuFile
->AppendSeparator();
297 menuFile
->Append(Exec_ClearLog
, _T("&Clear log\tCtrl-C"),
298 _T("Clear the log window"));
299 menuFile
->AppendSeparator();
300 menuFile
->Append(Exec_Quit
, _T("E&xit\tAlt-X"), _T("Quit this program"));
302 wxMenu
*execMenu
= new wxMenu
;
303 execMenu
->Append(Exec_SyncExec
, _T("Sync &execution...\tCtrl-E"),
304 _T("Launch a program and return when it terminates"));
305 execMenu
->Append(Exec_AsyncExec
, _T("&Async execution...\tCtrl-A"),
306 _T("Launch a program and return immediately"));
307 execMenu
->Append(Exec_Shell
, _T("Execute &shell command...\tCtrl-S"),
308 _T("Launch a shell and execute a command in it"));
309 execMenu
->AppendSeparator();
310 execMenu
->Append(Exec_Redirect
, _T("Capture command &output...\tCtrl-O"),
311 _T("Launch a program and capture its output"));
312 execMenu
->Append(Exec_Pipe
, _T("&Pipe through command...\tCtrl-P"),
313 _T("Pipe a string through a filter"));
315 execMenu
->AppendSeparator();
316 execMenu
->Append(Exec_OpenFile
, _T("Open &file...\tCtrl-F"),
317 _T("Launch the command to open this kind of files"));
319 execMenu
->AppendSeparator();
320 execMenu
->Append(Exec_DDEExec
, _T("Execute command via &DDE...\tCtrl-D"));
321 execMenu
->Append(Exec_DDERequest
, _T("Send DDE &request...\tCtrl-R"));
324 wxMenu
*helpMenu
= new wxMenu(_T(""), wxMENU_TEAROFF
);
325 helpMenu
->Append(Exec_About
, _T("&About...\tF1"), _T("Show about dialog"));
327 // now append the freshly created menu to the menu bar...
328 wxMenuBar
*menuBar
= new wxMenuBar();
329 menuBar
->Append(menuFile
, _T("&File"));
330 menuBar
->Append(execMenu
, _T("&Exec"));
331 menuBar
->Append(helpMenu
, _T("&Help"));
333 // ... and attach this menu bar to the frame
336 // create the listbox in which we will show misc messages as they come
337 m_lbox
= new wxListBox(this, -1);
338 wxFont
font(12, wxFONTFAMILY_TELETYPE
, wxFONTSTYLE_NORMAL
,
339 wxFONTWEIGHT_NORMAL
);
341 m_lbox
->SetFont(font
);
344 // create a status bar just for fun (by default with 1 pane only)
346 SetStatusText(_T("Welcome to wxWindows exec sample!"));
347 #endif // wxUSE_STATUSBAR
350 // ----------------------------------------------------------------------------
351 // event handlers: file and help menu
352 // ----------------------------------------------------------------------------
354 void MyFrame::OnQuit(wxCommandEvent
& WXUNUSED(event
))
356 // TRUE is to force the frame to close
360 void MyFrame::OnClear(wxCommandEvent
& WXUNUSED(event
))
365 void MyFrame::OnAbout(wxCommandEvent
& WXUNUSED(event
))
367 wxMessageBox(_T("Exec wxWindows Sample\n© 2000-2001 Vadim Zeitlin"),
368 _T("About Exec"), wxOK
| wxICON_INFORMATION
, this);
371 void MyFrame::OnKill(wxCommandEvent
& WXUNUSED(event
))
373 long pid
= wxGetNumberFromUser(_T("Please specify the process to kill"),
385 static const wxString signalNames
[] =
387 _T("Just test (SIGNONE)"),
388 _T("Hangup (SIGHUP)"),
389 _T("Interrupt (SIGINT)"),
390 _T("Quit (SIGQUIT)"),
391 _T("Illegal instruction (SIGILL)"),
392 _T("Trap (SIGTRAP)"),
393 _T("Abort (SIGABRT)"),
394 _T("Emulated trap (SIGEMT)"),
395 _T("FP exception (SIGFPE)"),
396 _T("Kill (SIGKILL)"),
398 _T("Segment violation (SIGSEGV)"),
399 _T("System (SIGSYS)"),
400 _T("Broken pipe (SIGPIPE)"),
401 _T("Alarm (SIGALRM)"),
402 _T("Terminate (SIGTERM)"),
405 int sig
= wxGetSingleChoiceIndex(_T("How to kill the process?"),
407 WXSIZEOF(signalNames
), signalNames
,
412 wxFAIL_MSG( _T("unexpected return value") );
440 if ( wxProcess::Exists(pid
) )
441 wxLogStatus(_T("Process %d is running."), pid
);
443 wxLogStatus(_T("No process with pid = %d."), pid
);
447 wxKillError rc
= wxProcess::Kill(pid
, (wxSignal
)sig
);
448 if ( rc
== wxKILL_OK
)
450 wxLogStatus(_T("Process %d killed with signal %d."), pid
, sig
);
454 static const wxChar
*errorText
[] =
457 _T("signal not supported"),
458 _T("permission denied"),
459 _T("no such process"),
460 _T("unspecified error"),
463 wxLogStatus(_T("Failed to kill process %d with signal %d: %s"),
464 pid
, sig
, errorText
[rc
]);
469 // ----------------------------------------------------------------------------
470 // event handlers: exec menu
471 // ----------------------------------------------------------------------------
473 void MyFrame::DoAsyncExec(const wxString
& cmd
)
475 wxProcess
*process
= new MyProcess(this, cmd
);
476 m_pidLast
= wxExecute(cmd
, FALSE
/* async */, process
);
479 wxLogError(_T("Execution of '%s' failed."), cmd
.c_str());
485 wxLogStatus(_T("Process %ld (%s) launched."), m_pidLast
, cmd
.c_str());
491 void MyFrame::OnSyncExec(wxCommandEvent
& WXUNUSED(event
))
493 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
500 wxLogStatus(_T("'%s' is running please wait..."), cmd
.c_str());
502 int code
= wxExecute(cmd
, TRUE
/* sync */);
504 wxLogStatus(_T("Process '%s' terminated with exit code %d."),
509 void MyFrame::OnAsyncExec(wxCommandEvent
& WXUNUSED(event
))
511 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
521 void MyFrame::OnShell(wxCommandEvent
& WXUNUSED(event
))
523 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
530 int code
= wxShell(cmd
);
531 wxLogStatus(_T("Shell command '%s' terminated with exit code %d."),
536 void MyFrame::OnExecWithRedirect(wxCommandEvent
& WXUNUSED(event
))
538 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
546 switch ( wxMessageBox(_T("Execute it synchronously?"),
548 wxYES_NO
| wxCANCEL
| wxICON_QUESTION
, this) )
564 wxArrayString output
, errors
;
565 int code
= wxExecute(cmd
, output
, errors
);
566 wxLogStatus(_T("command '%s' terminated with exit code %d."),
571 ShowOutput(cmd
, output
, _T("Output"));
572 ShowOutput(cmd
, errors
, _T("Errors"));
577 MyPipedProcess
*process
= new MyPipedProcess(this, cmd
);
578 if ( !wxExecute(cmd
, FALSE
/* async */, process
) )
580 wxLogError(_T("Execution of '%s' failed."), cmd
.c_str());
586 m_running
.Add(process
);
593 void MyFrame::OnExecWithPipe(wxCommandEvent
& WXUNUSED(event
))
596 m_cmdLast
= _T("tr [a-z] [A-Z]");
598 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
605 wxString input
= wxGetTextFromUser(_T("Enter the string to send to it: "),
610 // always execute the filter asynchronously
611 MyPipedProcess2
*process
= new MyPipedProcess2(this, cmd
, input
);
612 int pid
= wxExecute(cmd
, FALSE
/* async */, process
);
615 wxLogStatus(_T("Process %ld (%s) launched."), pid
, cmd
.c_str());
617 m_running
.Add(process
);
621 wxLogError(_T("Execution of '%s' failed."), cmd
.c_str());
629 void MyFrame::OnFileExec(wxCommandEvent
& event
)
631 static wxString s_filename
;
633 wxString filename
= wxLoadFileSelector(_T("file"), _T(""), s_filename
);
637 s_filename
= filename
;
639 wxString ext
= filename
.AfterFirst(_T('.'));
640 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
643 wxLogError(_T("Impossible to determine the file type for extension '%s'"),
649 bool ok
= ft
->GetOpenCommand(&cmd
,
650 wxFileType::MessageParameters(filename
, _T("")));
654 wxLogError(_T("Impossible to find out how to open files of extension '%s'"),
662 // ----------------------------------------------------------------------------
664 // ----------------------------------------------------------------------------
668 bool MyFrame::GetDDEServer()
670 wxString server
= wxGetTextFromUser(_T("Server to connect to:"),
671 DIALOG_TITLE
, m_server
);
677 wxString topic
= wxGetTextFromUser(_T("DDE topic:"), DIALOG_TITLE
, m_topic
);
683 wxString cmd
= wxGetTextFromUser(_T("DDE command:"), DIALOG_TITLE
, m_cmdDde
);
692 void MyFrame::OnDDEExec(wxCommandEvent
& WXUNUSED(event
))
694 if ( !GetDDEServer() )
698 wxConnectionBase
*conn
= client
.MakeConnection("", m_server
, m_topic
);
701 wxLogError(_T("Failed to connect to the DDE server '%s'."),
706 if ( !conn
->Execute(m_cmdDde
) )
708 wxLogError(_T("Failed to execute command '%s' via DDE."),
713 wxLogStatus(_T("Successfully executed DDE command"));
718 void MyFrame::OnDDERequest(wxCommandEvent
& WXUNUSED(event
))
720 if ( !GetDDEServer() )
724 wxConnectionBase
*conn
= client
.MakeConnection("", m_server
, m_topic
);
727 wxLogError(_T("Failed to connect to the DDE server '%s'."),
732 if ( !conn
->Request(m_cmdDde
) )
734 wxLogError(_T("Failed to send request '%s' via DDE."),
739 wxLogStatus(_T("Successfully sent DDE request."));
744 #endif // __WINDOWS__
746 // ----------------------------------------------------------------------------
748 // ----------------------------------------------------------------------------
751 void MyFrame::OnIdle(wxIdleEvent
& event
)
753 size_t count
= m_running
.GetCount();
754 for ( size_t n
= 0; n
< count
; n
++ )
756 if ( m_running
[n
]->HasInput() )
763 void MyFrame::OnProcessTerminated(MyPipedProcess
*process
)
765 m_running
.Remove(process
);
769 void MyFrame::ShowOutput(const wxString
& cmd
,
770 const wxArrayString
& output
,
771 const wxString
& title
)
773 size_t count
= output
.GetCount();
777 m_lbox
->Append(wxString::Format(_T("--- %s of '%s' ---"),
778 title
.c_str(), cmd
.c_str()));
780 for ( size_t n
= 0; n
< count
; n
++ )
782 m_lbox
->Append(output
[n
]);
785 m_lbox
->Append(_T("--- End of output ---"));
788 // ----------------------------------------------------------------------------
790 // ----------------------------------------------------------------------------
792 void MyProcess::OnTerminate(int pid
, int status
)
794 wxLogStatus(m_parent
, _T("Process %u ('%s') terminated with exit code %d."),
795 pid
, m_cmd
.c_str(), status
);
797 // we're not needed any more
801 // ----------------------------------------------------------------------------
803 // ----------------------------------------------------------------------------
805 bool MyPipedProcess::HasInput()
807 bool hasInput
= FALSE
;
809 wxInputStream
& is
= *GetInputStream();
812 wxTextInputStream
tis(is
);
814 // this assumes that the output is always line buffered
816 msg
<< m_cmd
<< _T(" (stdout): ") << tis
.ReadLine();
818 m_parent
->GetLogListBox()->Append(msg
);
823 wxInputStream
& es
= *GetErrorStream();
826 wxTextInputStream
tis(es
);
828 // this assumes that the output is always line buffered
830 msg
<< m_cmd
<< _T(" (stderr): ") << tis
.ReadLine();
832 m_parent
->GetLogListBox()->Append(msg
);
840 void MyPipedProcess::OnTerminate(int pid
, int status
)
842 // show the rest of the output
846 m_parent
->OnProcessTerminated(this);
848 MyProcess::OnTerminate(pid
, status
);
851 // ----------------------------------------------------------------------------
853 // ----------------------------------------------------------------------------
855 bool MyPipedProcess2::HasInput()
859 wxTextOutputStream
os(*GetOutputStream());
860 os
.WriteString(m_input
);
865 // call us once again - may be we'll have output
869 return MyPipedProcess::HasInput();