Redirecting stdin - freopen alternative

This is a discussion on Redirecting stdin - freopen alternative within the C Programming forums, part of the General Programming Boards category; I'm currently redirecting in a non-portable manner the standard input as: Code: freopen ("/dev/tty", "r", stdin); which /dev/tty always points ...

  1. #1
    Registered User
    Join Date
    Nov 2010
    Posts
    4

    Question Redirecting stdin - freopen alternative

    I'm currently redirecting in a non-portable manner the standard input as:

    Code:
    freopen ("/dev/tty", "r", stdin);
    which /dev/tty always points to the user's terminal. This helps me to read from input in a non-blocking manner.

    I can perform well something like:

    Code:
      while(fgets(buf, sizeof(buf), stdin))
        fputs(buf, stdout);
    
      freopen("/dev/tty", "rw", stdin);
      // continue with the rest of the code in a non-blocking manner
    I'm wondering what would be an alternative to freopen, perhaps using I/O multiplexing. such as select()? or a thread that blocks on reading stdin?

    Any alternative sample code would be appreciated.

    Platforms: BSDs, Linux

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,452
    Sure, stdin is file descriptor 0, and you can use that in an fd_set passed to select()

    You might need to be careful between select detecting a single character being available, and fgets potentially blocking until a newline is entered.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User
    Join Date
    Nov 2010
    Posts
    4
    Could you elaborate a little bit more about using select() instead of freopen? Or how would that apply on the above case? Thanks for your reply.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. freopen....
    By roaan in forum C Programming
    Replies: 7
    Last Post: 08-23-2010, 08:50 AM
  2. Another syntax error
    By caldeira in forum C Programming
    Replies: 31
    Last Post: 09-05-2008, 01:01 AM
  3. Redirecting STDOUT to STDIN of a child process
    By 0xception in forum Linux Programming
    Replies: 4
    Last Post: 09-13-2005, 11:58 PM
  4. Redirecting stdout, stderr and stdin
    By iwabee in forum Linux Programming
    Replies: 9
    Last Post: 05-16-2005, 05:42 PM
  5. stdin question
    By oomen3 in forum C Programming
    Replies: 6
    Last Post: 02-19-2003, 01:52 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21