Q: Reading from stdin without blocking?

Discussion in 'C++' started by Jakob Bieling, May 8, 2005.

  1. Hi,

    whenever I try to read input from stdin, the called function (ie.
    std::cin.read ()) blocks until my buffer is full. But I want to function
    to return immediately, regardless of having read something or not. Is
    this possible? Here's the tiny code that blocks:

    #include <iostream>

    int main ()
    {
    char tmp [64];
    std::cin.read (tmp, sizeof tmp);
    }


    Thank you
    --
    jb

    (reply address in rot13, unscramble first)
    Jakob Bieling, May 8, 2005
    #1
    1. Advertising

  2. Jakob Bieling

    Rolf Magnus Guest

    Jakob Bieling wrote:

    > Hi,
    >
    > whenever I try to read input from stdin, the called function (ie.
    > std::cin.read ()) blocks until my buffer is full. But I want to function
    > to return immediately, regardless of having read something or not. Is
    > this possible?


    No. Not in Standard C++. What you can try is check if something is available
    before reading, but it isn't guaranteed to work in all circumstances. It
    might or might not on your platform. std::cin.rdbuf()->in_avail() should
    (but doesn't need to) return the number of characters available for
    reading.
    If you want true non-blocking IO, you need to resort to system-specific
    functionality.

    > Here's the tiny code that blocks:
    >
    > #include <iostream>
    >
    > int main ()
    > {
    > char tmp [64];
    > std::cin.read (tmp, sizeof tmp);
    > }
    >
    >
    > Thank you
    Rolf Magnus, May 8, 2005
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Hendra Gunawan
    Replies:
    1
    Views:
    12,518
    Allan Herriman
    Apr 8, 2004
  2. Andre Kelmanson

    blocking i/o vs. non blocking i/o (performance)

    Andre Kelmanson, Oct 10, 2003, in forum: C Programming
    Replies:
    3
    Views:
    922
    Valentin Tihomirov
    Oct 12, 2003
  3. Charlie Zender

    Reading stdin once confuses second stdin read

    Charlie Zender, Jun 19, 2004, in forum: C Programming
    Replies:
    6
    Views:
    783
    Dan Pop
    Jun 21, 2004
  4. hg
    Replies:
    7
    Views:
    502
    Gabriel Genellina
    Jan 15, 2007
  5. Stefano Sabatini
    Replies:
    6
    Views:
    289
    Stefano Sabatini
    Jul 29, 2007
Loading...

Share This Page