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

Community
  • 1
  • 1
Johan de Vries
  • 175
  • 1
  • 9

1 Answers1

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

Petr Skocik
  • 58,047
  • 6
  • 95
  • 142
  • 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? – Johan de Vries Feb 07 '17 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 07 '17 at 15:44
  • Followup question: http://stackoverflow.com/questions/42117551/race-condition-in-starting-up-sub-processes-causes-reading-from-pipe-to-hang – Johan de Vries Feb 08 '17 at 15:45