Search code examples
c++clinuxstdin

Accessing stdin with 2 programs at the same time in Linux/Unix


I have read that stdin is a file in Linux/Unix. So, can 2 programs access the same stdin at the same time?? If yes, then how can this be done with C/C++??


Solution

  • Yes, this is possible. It's not a feature of specific programming languages, it's a feature of the operating system you're running on.

    Look at this shell script example:

    printf 'a\nb\n' | { { read x && echo $x; } <&0 & { read y && echo $y; }; }
    

    Here, { read x && echo $x; } will (likely) be executed as a separate process, and the same applies to { read y && echo $y; }. Both processes read from the same stdin, which is the a\nb\n output from printf, so you should expect one of the processes to read a, and another to read b.

    Worth pointing out is that this doesn't let both programs read both lines of input. Whichever program is first to read will see that bit of input. If you do need the same lines of input to go to two separate programs, you will need a program which copies the input to two different files or file descriptors. An example of a Unix utility which does this is tee. You can check to see how that's implemented for more details, if needed.