I reversed statements in if/else, corrected now.
I am reading a code snippet from Advanced Programming in the UNIX® Environment:
The program tests its standard input to see whether it is capable of seeking.
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
int main(void){
if(lseek(STDIN_FILENO,0, SEEK_CUR) == -1)
printf("cannot seek\n");
else{
printf("seek ok\n");
}
}
I compile and run it (under Ubuntu 18.04.2 LTS) but don't understand the following behaviors.
//1
$ ./a.out
cannot seek
//2
$ ./a.out < /etc/passwd
seek OK
//3
$ cat < /etc/passwd | ./a.out
cannot seek
//4
$ ./a.out < /var/spool/cron/FIFO
cannot seek
Why //1 is cannot seek? Empty stdin should be able to seek I think. Is it because stdin has not been opened yet? Because I heard that normally stdin, stdout and stderr are opened when a program starts to run.
Why //2 is OK and //3 is not? I think they are the same.
seek OKwith the given program on OpenBSD (cat file | ./a.outreturnsseek OKthough). There's something wonky about the code. The terminal device (which is attached to thea.outprocess when no redirection is done) is not seekable../a.out <&-. Notice that the if/else are reversed in that code snippet ;-) (and that that's not a reliable way to test whether a file is seekable).