Poll

Nemanja Boric via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Dec 23 04:51:29 PST 2016


What's in the `core.sys.posix.poll` is just a C wrapper, meaning 
if you use  functions declared there, you're just calling the 
same one you would do in C, so it's very likely that you're doing 
something different in D and C program. Here's the example that 
works for me:

```

void main()
{
     import core.stdc.stdio: fileno, stdin;
     import core.sys.posix.poll: poll, pollfd, POLLIN;
     import std.stdio: writeln, write, readln;
     import std.exception: enforce;

     pollfd fds;
     fds.fd = fileno(stdin);
     fds.events = POLLIN;

     for (;;)
     {
         int ret = poll(&fds, 1, -1);
         switch (ret)
         {
             case POLLIN:
                 auto data = readln();
                 write("Data on stdin: ", data);
                 break;
             case 0:
                 writeln("timeout");
                 break;
             case -1:
             default:
                 enforce(false, "Error");
         }
     }
}
```

> > If anyone has any suggestions, they would be much appreciated.
> Really all I need is a way of checking if a stream / file will 
> block if I read it.

Be very careful here, poll works on the readiness principle, and 
POSIX enforces that the regular files are always ready for 
reading and writing, meaning that this will not work.

http://pubs.opengroup.org/onlinepubs/009695399/functions/poll.html

> Regular files shall always poll TRUE for reading and writing.

Nemanja

On Friday, 23 December 2016 at 11:07:49 UTC, LeqxLeqx wrote:
> I've recently been attempting to detect whether or not stdin 
> would block a read if I tried. I have attempted to use the 
> /core/sys/posix/poll.d but that seems to be always returning 
> '1' whether or not stdin has anything on it, whereas for the 
> corresponding program written in C, it will return 1 only if 
> there is something on stdin.
>
> If anyone has any suggestions, they would be much appreciated. 
> Really all I need is a way of checking if a stream / file will 
> block if I read it.
>
> Thanks




More information about the Digitalmars-d-learn mailing list