0

In C / C++ you read stdout from a sub process via dup2( ..., STDERR_FILENO)[1]. I don't really understand what dup2 does; can I do it twice for two sub processes that are running at the same time? I'm seeing an issue with my existing implementation where one them isn't able to finish reading STDERR and I'm wondering if that's an implementation bug or whether it's just not possible.

Edit: They're started by separate threads. Starting and stopping may interleave in any way.

[1] e.g. like Linux 3.0: Executing child process with piped stdin/stdout

1 Answer 1

3

Think of a file descriptor as a ref-counted/smart indirect pointer to a kernel-maintained file object. dup (dup2, dup3) duplicates the smart "pointer" by incrementing the kernel-maintained file object's refcount. close decrements the refcount and destructs the kernel-maintained file object if the refcount becomes 0.

These file objects may be shared by multiple processes, which usually happens when a process forks (a fork also increments the refcounts of the file objects pointed to by the inherited filedescriptors (and so does sending a file descriptor via a UNIX socket)).

(Keeping this model in mind is particularly important when you deal with pipe file descriptors duplicated by forking, because a pipe's read end will only get an EOF when all of its write ends (in all processes that have a fd referring to that write end) have been closed.)

3
  • So both processes would write to the same file descriptor? So how does the parent tell the difference between which process the data comes from? Feb 7, 2017 at 15:42
  • 1
    @JohandeVries, unless you print the ID of the child process, there is no way of knowing which process wrote to it.
    – R Sahu
    Feb 7, 2017 at 15:44
  • Followup question: stackoverflow.com/questions/42117551/… Feb 8, 2017 at 15:45

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.