2 // "$Id: howto-add_fd-and-popen.cxx 8194 2011-01-05 22:28:39Z AlbrechtS $"
4 // How to use popen() and Fl::add_fd() - erco 10/04/04
5 // Originally from erco's cheat sheet, permission by author.
7 // Shows how the interface can remain "alive" while external
8 // command is running and outputing occassional data. For instance,
9 // while the command is running, keyboard navigation works,
10 // text can be highlighted, and the interface can be resized.
12 // Copyright 2010 Greg Ercolano.
13 // Copyright 1998-2010 by Bill Spitzak and others.
15 // This library is free software; you can redistribute it and/or
16 // modify it under the terms of the GNU Library General Public
17 // License as published by the Free Software Foundation; either
18 // version 2 of the License, or (at your option) any later version.
20 // This library is distributed in the hope that it will be useful,
21 // but WITHOUT ANY WARRANTY; without even the implied warranty of
22 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
23 // Library General Public License for more details.
25 // You should have received a copy of the GNU Library General Public
26 // License along with this library; if not, write to the Free Software
27 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
30 // Please report all bugs and problems on the following page:
32 // http://www.fltk.org/str.php
36 #include <FL/Fl_Window.H>
37 #include <FL/Fl_Multi_Browser.H>
40 # define PING_CMD "ping -n 10 localhost" // 'slow command' under windows
43 # define pclose _pclose
45 # include <unistd.h> // non-MS win32 compilers (untested)
49 # define PING_CMD "ping -i 2 -c 10 localhost" // 'slow command' under unix
55 // Handler for add_fd() -- called whenever the ping command outputs a new line of data
56 void HandleFD(int fd
, void *data
) {
57 Fl_Multi_Browser
*brow
= (Fl_Multi_Browser
*)data
;
59 if ( fgets(s
, 1023, G_fp
) == NULL
) { // read the line of data
60 Fl::remove_fd(fileno(G_fp
)); // command ended? disconnect callback
61 pclose(G_fp
); // close the descriptor
62 brow
->add(""); brow
->add("<<DONE>>"); // append msg indicating command finished
65 brow
->add(s
); // line of data read? append to widget
68 int main(int argc
, char *argv
[]) {
69 Fl_Window
win(600,600);
70 Fl_Multi_Browser
brow(10,10,580,580);
71 if ( ( G_fp
= popen(PING_CMD
, "r") ) == NULL
) { // start the external unix command
72 perror("popen failed");
75 Fl::add_fd(fileno(G_fp
), HandleFD
, (void*)&brow
); // setup a callback for the popen()ed descriptor
82 // End of "$Id: howto-add_fd-and-popen.cxx 8194 2011-01-05 22:28:39Z AlbrechtS $".