Tzafrir
Tzafrir

Reputation: 669

redirect stdin from file descriptor in linux c

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.

  1. open FD
  2. duplicate to stdin.
  3. close stdin
  4. close the original fd

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

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134396

As per the man page

int dup2(int oldfd, int newfd);

If oldfd is a valid file descriptor, and newfd has the same value as oldfd, then dup2() does nothing, and returns newfd.

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

Related Questions