在dup2之后,流还包含旧内容?

Bob*_*rbo 0 c unix redirect stream dup2

所以,如果我这样做:

dup2(0, backup); // backup stdin
dup2(somefile, 0); // somefile has four lines of content
fgets(...stdin); // consume one line
fgets(....stdin); // consume two lines
dup2(backup, 0); // switch stdin back to keyboard
Run Code Online (Sandbox Code Playgroud)

我在这一点上发现.. stdin仍然包含我没有消耗的两条线.这是为什么?因为无论重定向多少次,只有一个缓冲区?我如何摆脱剩下的两行,但是当我想回到它时,仍然记得我在somefile流中的位置?

Ric*_*ton 5

您还没有刷新stdin缓冲区.即使恢复了底层文件描述符,它也已经缓存了somefile的所有行.