Reputation: 669
I can't understand what's wrong with the following code. I perform exactly the same actions twice. It works for the first time, and fails for the second.
At the second time I get an error, at stage 4, which means the FD is already closed.
int fd =open("/path/to/some/file",0,"r");
if (dup2(fd,STDIN_FILENO)<0)
perror("dup_in");
if (close(STDIN_FILENO)<0)
perror("close_in");
if (close(fd)<0)
perror("close_fd");
//Up to here it works fine.
fd =open("/path/to/some/file",0,"r");
if (dup2(fd,STDIN_FILENO)<0)
perror("dup_in2");
if (close(STDIN_FILENO)<0)
perror("close_in2");
if (close(fd)<0) //<-- ERROR!
perror("close_fd2"); //<--close_fd2: Bad file descriptor
Upvotes: 0
Views: 4540
Reputation: 134396
As per the man page
int dup2(int oldfd, int newfd);
If
oldfd
is a valid file descriptor, andnewfd
has the same value as oldfd, thendup2()
does nothing, and returnsnewfd
.
So, in your second case, open()
uses the least available FD, 0
[free'd by last call to close()
]. That's how oldFD
and newFD
becomes the same, creating the error.
Note: Before using the fd
returned by open()
, you should always verify the sucess of open()
call.
Upvotes: 3