> I want to write a small program, that works as a filter for lpr.
> It should read all command-line parameters and the standard-input
> stdin,
> do some accounting
> and then pass all command-line parameters to lpr and pipe the stdin to
> the stdin of lpr.
> Now my problem is: if there is a Input at stdin all works fine with
> while (cin.good()){
> ch=cin.get();
> write(fd[1],&ch,1);//ch is written to the write-side of the pipe,
> which is connected to
> // lpr
> count++; //only fpr accounting purposes.
> }
> But if there isn't any input at stdin, cin.good() returns true, an my
> program will
> wait at ch=cin.get() forever. :-(
> Is there a way to detect, that nothing comes from stdin and to give up
> waiting?
> Or is the only way to check the parameters whether a input from stdin is
> expected or not?
> (in my case, whether the last parameter is a file or not).
I'm no C++ programmer, so bear with me:
You are a little unclear by what you mean by "nothing comes from stdin".
If the input is exhausted (all data from a file has been read or the
sending process has closed its side of the pipe/connection), then you
have the "End-Of-File" condition. Under Linux (and most/all Unices),
this will result in the read() system call returning 0. C++ should
provide some means of checking this. I just borrowed the Stroustrup
book from a colleague and it seems that cin.get(ch) will return 0 in
this case, so you could write
while (cin.good() && cin.get(ch)) {
write(fd[1], &ch, 1);
count++;
}
Another possibility is the "eof" function:
while (cin.good() && !cin.eof()) {
ch = cin.get();
write(fd[1], &ch, 1);
count++;
}
(Again, I'm no C++ person and this is absolutely untested)
If, however, you mean that no input is received within a certain amount
of time, you might want to look at the alarm() system call. Set up an
alarm for e.g. 5 seconds before trying to read a character and, if a
character is read, reset the alarm to 0, else handle the timeout
condition.
I don't know how the, rather high-level, C++-streams cooperate with
alarm.
YMMV.
HTH,
--
Josef M?llers (Pinguinpfleger bei FSC)
If failure had no penalty success would not be a prize
-- T. Pratchett