What happens to the file descriptor table in parent process after calling dup2 and execvp in the child process?

StackOverflow https://stackoverflow.com//questions/25050117

  •  21-12-2019
  •  | 
  •  

Question

I am coding a simple shell program but unsure of what happens to the file descriptor table after dup2() and execvp. So I have a parent process waiting for child process to end(waitpid) but when it loops back to wait for the next user input, how come does the file descriptor table I modified using dup2 in child process not persist in the parent process? Is it because execvp resets the file descriptor table back to the original?

EDIT: I figured it out. The fork function actually makes a separate copy of the program image, including file descriptor table so the parent process's fd table is unaffected.

Was it helpful?

Solution

Nothing. The child process gets a copy of the parent's file descriptors when it's created by fork(), but changes it makes after that aren't shared back to the parent.

(Note that, while the file descriptor table is not shared with the parent, the state of the file descriptors themselves is! For instance, if you seek() on a file descriptor that a child process inherited from its parent, that affects the copy in the parent as well.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top