What you are trying to do is get stdin
back to your control (terminal input) after a redirection. According to the C-FAQ you can't do it in a portable way:
There is no portable way of doing this. Under Unix, you can open the special file /dev/tty. Under MS-DOS, you can try opening the ``file'' CON, or use routines or BIOS calls such as getch which may go to the keyboard whether or not input is redirected.
But, if portability is not an issue, we can try a little work around (not optimal):
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char buf[1001], fname[10];
FILE *fp;
int i = 0;
while(1) {
if(fgets(buf, 1000, stdin)) {
sprintf(fname, "mf%d", i++);
if(!(fp = fopen(fname, "w"))) {
perror("fopen");
continue;
}
fprintf(fp, buf);
fclose(fp);
}
if(!(stdin = fopen("/dev/tty", "r"))) {
perror("stdin");
exit(0);
}
}
return 0;
}
The thing is, when you run the program, go to another terminal and get it's PID (ps aux | grep myprog
). Say the PID is 12345 Then you do ls -la /proc/12345/fd
and you'll see that the descriptor 0 is a pipe (done by the shell). So you need another stdin... and in Linux you can use fopen("/dev/tty", "r")
, but again, not portable.