Debian Codegraph @

examples/howto-add_fd-and-popen.cxx

raw symbols SCIP
1 //
2 // "$Id$"
3 //
4 // How to use popen() and Fl::add_fd() - erco 10/04/04
5 // Originally from erco's cheat sheet, permission by author.
6 //
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.
11 //
12 // Copyright 2010 Greg Ercolano.
13 // Copyright 1998-2010 by Bill Spitzak and others.
14 //
15 // This library is free software. Distribution and use rights are outlined in
16 // the file "COPYING" which should have been included with this file. If this
17 // file is missing or damaged, see the license at:
18 //
19 // http://www.fltk.org/COPYING.php
20 //
21 // Please report all bugs and problems on the following page:
22 //
23 // http://www.fltk.org/str.php
24 //
25 #include <stdio.h>
26 #include <FL/Fl.H>
27 #include <FL/Fl_Window.H>
28 #include <FL/Fl_Multi_Browser.H>
29
30 #ifdef WIN32
31 # define PING_CMD "ping -n 10 localhost" // 'slow command' under windows
32 # ifdef _MSC_VER
33 # define popen _popen
34 # define pclose _pclose
35 # else /*_MSC_VER*/
36 # include <unistd.h> // non-MS win32 compilers (untested)
37 # endif /*_MSC_VER*/
38 #else
39 # include <unistd.h>
40 # define PING_CMD "ping -i 2 -c 10 localhost" // 'slow command' under unix
41 #endif
42
43 // GLOBALS
44 FILE *G_fp = NULL;
45
46 // Handler for add_fd() -- called whenever the ping command outputs a new line of data
47 // Note: FL_SOCKET as 1st argument is used to fix a compiler error(!) on Windows 64-bit.
48 // Unfortunately we need this in FLTK 1.3 - should hopefully be fixed in 1.4 with a better solution.
49 void HandleFD(FL_SOCKET fd, void *data) {
50 Fl_Multi_Browser *brow = (Fl_Multi_Browser*)data;
51 char s[1024];
52 if ( fgets(s, 1023, G_fp) == NULL ) { // read the line of data
53 Fl::remove_fd(fileno(G_fp)); // command ended? disconnect callback
54 pclose(G_fp); // close the descriptor
55 brow->add(""); brow->add("<<DONE>>"); // append msg indicating command finished
56 return;
57 }
58 brow->add(s); // line of data read? append to widget
59 }
60
61 int main(int argc, char *argv[]) {
62 Fl_Window win(600,600);
63 Fl_Multi_Browser brow(10,10,580,580);
64 if ( ( G_fp = popen(PING_CMD, "r") ) == NULL ) { // start the external unix command
65 perror("popen failed");
66 return(1);
67 }
68 Fl::add_fd(fileno(G_fp), HandleFD, (void*)&brow); // setup a callback for the popen()ed descriptor
69 win.resizable(brow);
70 win.show(argc, argv);
71 return(Fl::run());
72 }
73
74 //
75 // End of "$Id$".
76 //