[vox-tech] a better scanf?? (C-programming question)

Tim Riley vox-tech@lists.lugod.org
Fri, 18 Apr 2003 20:14:43 -0700


Andy Campbell wrote:

> >
> > I'm trying to read your intent from the code above,
> > and it seems to be "run a process until
> > it finishes or let me press 'x' if I run out of patience." If
> > that's the case,
> > then it'll be much easier to interrupt the process with <ctl>c instead.
>
> really the intent of this program is "let me see if I can get the string
> 'Waiting...' to print over and over again until I input any letter (other
> than x) at which point waiting will then print over and over again....
>

Maybe fork() and signal() are what you need. It's not as fast as using
threads because it forks a whole new process instead of running inside
a shared process control block, but it's easy to work with.

#include <stdio.h>
#include <termio.h>
#include <signal.h>

struct termios new_settings;
struct termios stored_settings;

void set_keypress(void) {
        tcgetattr(0,&stored_settings);
        new_settings = stored_settings;
        new_settings.c_lflag &= (~ICANON);
        new_settings.c_cc[VTIME] = 0;
        tcgetattr(0,&stored_settings);
        new_settings.c_cc[VMIN] = 1;
        tcsetattr(0,TCSANOW,&new_settings);
}

void process_keystroke_x()
{
        printf( "Caught x\n" );
        signal( SIGUSR1, process_keystroke_x );
}

int main( int argc, char *argv )
{
        int c;
        int child_process_id;

        set_keypress();
        signal( SIGUSR1, process_keystroke_x );
        child_process_id = fork();

        if ( child_process_id == 0 ) {  /* If child */
                while( 1 ) {
                        printf( "Waiting...\n" );
                        sleep( 5 );
                }
        }

        while( 1 ) { /* If parent */
                c = getchar();
                if ( c == 'x' ) kill( child_process_id, SIGUSR1 );
        }
}

>
> >
> > Another possibility of intent is to prompt the user with a list
> > of choices,
> > assigning each choice a single letter to press, and have that choice be
> > recorded without having to press <enter>. If that's the case, then Ryan's
> > reference to the function "set_keypress()" will work. However,
> > the function
> > as posted has some bugs in it. Here is a complete program with the
> > function working.
>
> It's not just pressing enter....I actually implemented the set_keypress
> function successfully (not shown in the code obviuosly) but it is not what I
> want. It still stopped the program flow until I entered one character, at
> which point it continued through once and got hung up on the getchar()
> function again.
>
> I want it to run through the code continuosly, and then when I input a char,
> it interrupts the program and stores the value.
>
> _______________________________________________
> vox-tech mailing list
> vox-tech@lists.lugod.org
> http://lists.lugod.org/mailman/listinfo/vox-tech