Note that there are some explanatory texts on larger screens.

plurals
  1. PONonblocking Get Character
    text
    copied!<ul> <li>Platform: Linux 3.2.0 x86 (Debian 7)</li> <li>Compiler: GCC 4.7.2 (Debian 4.7.2-5)</li> </ul> <p>I am writing a function that reads a single character from stdin if a character is already present in stdin. If stdin is empty the function is suppose to do nothing and return -1. I googled nonblocking input and was pointed to <a href="http://pubs.opengroup.org/onlinepubs/009695399/functions/poll.html">poll()</a> or <a href="http://pubs.opengroup.org/onlinepubs/009695399/functions/select.html">select()</a>. First I tried to use select() but I could not get it to work so I tried poll() and reached the same conclusion. I am not sure what these functions do exactly but from what I understand of poll()'s documentation if I call it like so:</p> <pre><code>struct pollfd pollfds; pollfds = STDIN_FILENO; pollfds.events = POLLIN; poll(pollfds, 1, 0); </code></pre> <p>if(pollfds.revents &amp; POLLIN) will be true if "Data other than high-priority data may be read without blocking.". But poll() always times out in my test situation. How I test the function could be the problem but the functionality I want is exactly what I am testing for. Here is the function currently and the test situation as well.</p> <pre><code>#include &lt;poll.h&gt; #include &lt;stdio.h&gt; #include &lt;unistd.h&gt; int ngetc(char *c) { struct pollfd pollfds; pollfds.fd = STDIN_FILENO; pollfds.events = POLLIN; poll(&amp;pollfds, 1, 0); if(pollfds.revents &amp; POLLIN) { //Bonus points to the persons that can tell me if //read() will change the value of '*c' if an error //occurs during the read read(STDIN_FILENO, c, 1); return 0; } else return -1; } //Test Situation: //Try to read a character left in stdin by an fgets() call int main() { int ret = 0; char c = 0; char str[256]; //Make sure to enter more than 2 characters so that the excess //is left in stdin by fgets() fgets(str, 2, stdin); ret = ngetc(&amp;c); printf("ret = %i\nc = %c\n", ret, c); return 0; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload