clinuxpipestdin

Handling of quitting the pipe / stdin on linux when no input received


Say I have an image viewer program. I would want to view images in these two ways:

imageviewer [list of files] // scenario A
[list of files] | imageviewer // scenario B

and using one method shall not just invalidate the other method, so this should logically also work:

[list of files] | imageviewer [list of files] // scenario C

The way I thought about doing this, involves creating a thread that exclusively does getchar() (and handles a potential string) until it gets an EOF where it quits the thread gracefully.

This works for all scenarios, with a massive issue arising in scenario A. If I never get input, I never get any EOF due to not getting any characters, and then blocking the thread, having to kill (ctrl+c) the program to quit, which is very ugly, since I don't gracefully exit it, and the program still runs when you wanted to quit.


Solution

  • The issue that solved my problem, is simply calling isatty - through that I could know in advance if I have pending input or not.

    Apparently I made people confused, that I was proposing 'it should be able to do Z because X and Y works':

    echo files | imageviewer other-files

    With semi-good reasoning in my opinion.

    Suggesting to just not parse piped input is boring, as I am mainly the sole user of the program tbh, and I did want to sometimes pipe files into it, rather than doing imageviewer $(command) .

    Suggesting to use another program (xargs) to achieve also the same thing kinda works, but I find that a lame solution, and I'd have to type more (as if I'm not typing enough already) :D

    So, I think I will adopt some sort of hybrid (which is ONLY possible because of the isatty call)

    1. if no files passed as arguments, check stdin

    2. if files parsed, don't check stdin

    3. optionally through a flag, enable both methods to work

    Appreciate the insights on why it might be bad to just do random things.

    ---

    P.S. yes I am playing with an image viewer, yes it does exist, it is here https://github.com/rphii/c-image-viewer -- probably a TON of things wrong with it. it evolved from an experimental project to something "larger" than I initially planned, and I have not yet caught up on it -- whatever, I'm not here to ramble on about how imperfect and ugly the code is, so yea look at it or not I don't care. just wanted to show that I am actually using the solution suggested.