I think what you're looking for is an unget_char() routine to work with a getchar() routine. (Actually unget_str(), but it's easier to explain at the character level. And it has historical precedence in C, although it's neithe ANSI nor Posix standard.)

To make this work rolling your own, you need to pull all input from a single routine, a getchar() routine, and that routine needs to have an extra buffer that you can put characters back into, when you don't want them yet. getchar() takes bytes from that extra buffer, in order, and only when the extra buffer's empty does it go to STDIN itself.

This is the only way to maintain the sequence of characters comming in. If you try to load them back in by stuffing them into STDIN, then you will always have a race condition where a new character typed in can get stuffed in after you took characters out, but before you put them back in. This will happen rarely and unpredictably, and possibly more often when the system is loaded. It will probably not show up in testing.

Update: Looks like I misunderstood what the OP wanted. I should have read "process" as "OS process", which makes sense to do, but I missed it. Oh well, it was a decent answer to a different question, I think. (And thanks to [id://betterworld] for pointing out the error.)


In reply to Re: non-destructive read on stdin by rodion
in thread non-destructive read on stdin by jeremyh

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.