Reputation: 109
I am very much new to IPC programming in C. I had a very basic question, why many of our C codes use dup2 to make stdout as write head and stdin as read head for the PIPE. Is there any benefit, comapred to an array of integer type and using the array as an input to pipe call?
Upvotes: 0
Views: 172
Reputation: 753455
Many C programs are written as filters, which (by default) read from standard input and write to standard output. The plumbing with pipes exploits, and supports, idioms of sending the output from one program to the input of another, as with:
ls | wc -l
That's why you very often end up with code connecting the pipe file descriptors to standard input or standard output. If you needed to make programs read from, or write to, arbitrary file descriptors, you'd have to supply control arguments to tell them what to do. Granted, these days on systems such as Linux with the /dev/fd
file system, it would be doable, but that's a recent innovation that was not available when many programs were first written. You could get nearly the same result as above using:
ls | wc -l /dev/fd/0
but wc
would echo the file name in this case, whereas it does not echo the file name when no name is given as in the first example.
Upvotes: 2