Johan de Vries
Johan de Vries

Reputation: 175

Can I redirect stdout for two sub processes?

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

Upvotes: 0

Views: 265

Answers (1)

Petr Skocik
Petr Skocik

Reputation: 60058

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.)

Upvotes: 3

Related Questions