-3

how would I make it so that the fd of stdin returns to its original "file destination"? Could this be accomplished by originally forking, doing what I need to using the child process and then killing that child, leaving me back to the parent with the original file descriptors for things? Are file descriptors shared between parents and children actively?

Myron
  • 11
  • 1
    Lots of questions, little code. – Cheatah Dec 05 '21 at 19:22
  • not actively. at fork() the child has the same file-descriptors as its parent, bound to the same resources, but if the child (resp. the parent) uses dup2() on a file-descriptor, the parent (resp. the child) will not automatically perform the same redirection (the same goes for close()...). – prog-fh Dec 05 '21 at 19:33

1 Answers1

1

That would work. Changes to the child's stdin have no effect on the parent.

Stuff like file position is shared as long as the fds refer to the same stream because that's a property of the stream. But re-opening it or dupping onto it associates the descriptor with a different stream.

ikegami
  • 367,544
  • 15
  • 269
  • 518
  • *Changes to the child's stdin have no effect on the parent.* [It actually can in POSIX systems](https://pubs.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html#tag_15_05_01), as the parent and the child would still share the same underlying *file description*. So calls such as `lseek()` or `read()`/`write()` can change the position of more than one *file descriptor*. I can't find anything right now that links `fseek()` and `lseek()`, so it's open how changing the state of a file *description* affects the state of a *stream* that shares the *description* via another *descriptor*. – Andrew Henle Dec 05 '21 at 21:37
  • @Andrew Henle The answer already says that. – ikegami Dec 05 '21 at 21:56
  • In my experience, someone who doesn't understand the way POSIX `dup()`'d file descriptors still refer to the same file **description** would read "dupping onto it associates the descriptor with a different stream" and wind up surprised to find that the two different file **descriptors** would share state. Given that it takes POSIX something like 14 paragraphs and a long bullet list to describe the interaction between streams, file descriptors, and file descriptions, I thought it'd be too easy for a new programmer to mess up. (Yeah, I got bit bad once long ago...) – Andrew Henle Dec 05 '21 at 22:26