I cannot for the life of me get my head fully around dup2()
.
int fd = open("data", O_RDONLY);
/* open the disk file */
int newfd = dup2(fd,0);
/* close 0, dup fd to 0 */
if( newfd != 0)
{
fprintf(stderr,"Could not duplicate fd to 0\n");
exit(1);
}
close(fd);
So I understand that dup2()
in this case will close 0 (standard keyboard input for stdin), it will then make stdin read from the file data, but why would you then close(fd)
? I thought fd was what stdin is reading from now?