View Full Version : close stdin pipe

02-16-2011, 07:54 AM
Hey gang!

I'm not sure if this is bash specific, and I do want it to work as a multi-platform ansi compliant utility.

The program takes input from stdin, so eg:

echo "some data" | theprogram

However, once that data is piped in and saved in a buffer, some user input is needed:

#include <stdio.h>

int main(void) {
char buffer[4096], ch;
int c = 0;

/* get data from input pipe */
while ((ch = getchar())) {
if (feof(stdin) || c == 4096) break;
buffer[c++] = ch;

/* data complete, now: */
while ((ch = getchar())) {
printf("%d ",ch);

return 0;

The feof() happens, but after that there is a continuous and unstoppable stream of EOF characters:

-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 ...etc.

I can't off the top of my head think of a utility which accepts from stdin then switches to a TLI-ish control after the EOF, maybe this is why.

I've tried fclose() on stdin, forking, etc but nothing helps. I can't use threads because it must be cross-platform.

Is this just a no-go?

02-16-2011, 08:59 AM
fopen /dev/tty


02-16-2011, 09:46 AM
Thanx -- reading from a stream opened on /dev/tty instead of stdin does work and should do on POSIX, I imagine there is no universal solution.

02-16-2011, 03:42 PM
>> ... must be cross-platform.
Ah - for Windows you'll want CONIN$
Which can probably be fopen()'d as well.