Re: OT: capturing stdout & stderr to a GtkText



"Carlos A. Carnero Delgado" wrote:
> 
> Hello wizards,
> 
> this is not directly related to GTK+, but a) I really knew no other place to
> ask, and b) I'm building a GTK+ application that need this. In my app
> there's a window with a couple of GtkText's in it. One is used by the user
> to enter commands and the other to display the results of those commands.
> 
> Currently, I have Perl embedded to process whatever the user types (yup,
> it's possible to enter anything that Perl digs as ok, and it will executed.)
> However, if I enter "print 2;" the Perl interpreter will print 2 but on a
> terminal. How can I capture the stdout and stderr output of an embedded
> program like Perl? If I can capture, it'll be no problem adding it to the
> GtkText.

The following is simple way using popen which works well enough for me:



int   Command_fd = 0;
FILE *Command_fp = NULL;
gint  Command_input_tag = 0;

void
startCommand( char *cmd )
{
        if ( (Command_fp != NULL) )
        {
                pclose( Command_fp );
                Command_fp = NULL;
        }

        Command_fp = popen( cmd, "r" );
        if ( Command_fp == NULL )
        {
                Command_fp = NULL;
                Command_fd = -1;
                return;
        }

        Command_fd = fileno( Command_fp );

        Command_input_tag = gdk_input_add( Command_fd,
                    GDK_INPUT_READ,
                    commandResponse,
                    " " );
}

void
stopCommand()
{
        if ( Command_fp == NULL )       return;
        if ( Command_fd < 0  )          return;

        pclose( Command_fp );

        gdk_input_remove( Command_input_tag );

        Command_fp = NULL;
        Command_fd = -1;

        Command_input_tag = 0;
}

void
commandResponse( gpointer data, gint source, GdkInputCondition condition )
{
        char *p;
        char buf[129];
        int  len, numLines=0;

        // printf("commandResponse: source(%d), cond(%d)\n", source, condition );

        while ( (p = fgets( buf, 128, Command_fp )) != NULL )
        {
                len = strlen( buf );
                if ( len > 0 )
                        buf[len-1] = '\0';

                addMsgInfo( buf );       // function to add to text widget
                numLines++;
                return;
        }

        if ( numLines == 0 )
        {
                addMsgInfo( "Command Completed" ); // function to add to text widget
                stopCommand();
        }
}


If you need more(i.e. ability to kill child, muck with the environment, process
sdtout/stderr separately then use the fork/exec/kill routines ...)




[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]