Resetting select()??

Lars Henrik Mathiesen thorinn at skinfaxe.diku.dk
Fri Jul 6 04:08:09 AEST 1990


larocque at jupiter.crd.ge.com (David M. LaRocque) writes:
>I will do a 
>select() and process one chunk, but the next time I do a 
>select() no ready file descriptors will be found even though
>there are remaining chunks available.

> fp = fdopen(socket, "r");
> ...
> mask = 1 << socket;
> nfound = select(socket + 1, (fd_set *) &mask, (fd_set *) 0,
>		 (fd_set *) 0, &timeout);
> ...
> for (i = 0; i < 100; i++)
>    {
>    if ((next_char = getc(talk_fp)) == EOF)
>      {
>      fprintf(stderr, "This will not happen.\n");
>      exit(1);
>      }
>     chunk[i] = next_char;
>    }

As it turns out, your problem is not with select(), but with getc()
--- which makes it appropriate for this newsgroup.

getc() will use a relatively large buffer when reading from the socket
(nowadays, relatively large probably means some multiple of 4096). It
will get all the available chunks into that buffer, and select will
quite properly tell you that no more data are available (select cannot
and should not know about stdio buffers).

As far as I know, there are no portable ways of checking stdio
buffers. If you want to keep using stdio, you could put in a
'setbuf((char *)0)' after the fdopen. However, this will cause a
system call for each getc().

Furthermore, if you know that the data arrive in fixed-size chunks,
getc() is almost pure overhead already: The only non-obvious thing it
does is to call read again (through _filbuf) if it turns out that all
the data in a chunk didn't arrive at one time. I suggest that you
remove the fdopen and use:

    int nread, got;
    ...
    for (nread = 0; nread < 100; nread += got)
	if ((got = read(socket, &chunk[nread], 100 - nread)) <= 0)
	    break;
    if (nread < 100) {
	fprintf(stderr, "This will not happen.\n");
	exit(1);
    }

Oops, I think this strayed from C to UNIX again.
--
Lars Mathiesen, DIKU, U of Copenhagen, Denmark      [uunet!]mcsun!diku!thorinn
Institute of Datalogy -- we're scientists, not engineers.      thorinn at diku.dk



More information about the Comp.lang.c mailing list