[comp.unix.questions] SIGIO Signal Handling

battle@cs.utk.edu (David Battle) (11/15/90)

I am trying to write a game program which thinks on its opponents time, but
I would like for the user to be able to interrupt by typing a command to make
his move at any time.  I want it to be completely transparent to the user that
the machine is still processing rather than waiting patiently for input.  I
have something that works, but I am afraid that it is not safe/portable.  Could
someone give me some feedback?  Here is a short code fragment that shows what
I am trying to do; this is not intended to be a complete C program:

int gotsigio = 0;
int iochar;

crunch_gametree()
{
    while(1) {
        if(gotsigio) {
            return; /* early return to main routine to process input */
        }
        else {
            /* keep crunching */
        }
    }
}

void handler(sig, code, scp, addr)
int sig, code;
struct sigcontext *scp;
char *addr;
{
    gotsigio = 1;
    iochar = getchar();
}


set_async()
{
    signal(SIGIO, handler);
    fcntl(0, F_SETFL, FASYNC);
}

process_input()
{
    int c;

    if(!gotsigio) {
                    /* <- *** WHAT IF SIGIO OCCURS HERE?! *** */
        sigpause(0);
    }
    gotsigio = 0;
    c = iochar;
    /* process input character c */
}

main()
{
    set_async();
    while(!gameover()) {
        crunch_gametree();
        process_input();
    }
}

What I am concerned about is in process_input(), what if SIGIO happens after
the test in the if(!gotsigio) but before the call to sigpause(0).  This seems
like it could, at best, cause the program to loose input.

Any comments on a better (ie more portable/reliable) way to get the same
functionality would be much appreciated.

Please email a copy of any posts to me because I don't read this group
regularly.

						-David L. Battle
						 battle@cs.utk.edu