I pass 1
(stdout)/2
(stderr) to read
system call but it still works fine. Then I pass 0
(stdin) to write
system call and find out it works too!
int main(int argc, char** argv){
char buf[1024] = "abcdefghi\n";
write(0, buf, 10);
char readbuf[1024] = {0};
// read(1, readbuf, 10); works too
read(2, readbuf, 10);
write(2, readbuf, 10);
return 0;
}
output:
abcdefghi
hey stdin <-- I input this
hey stdin
Confused, I thought it should be an error.
Experiement:
Then I tried redirecting fd 2.
$ ./a.out 2>/dev/null
this time both the read and 2nd write is not 'visible'. The output is
abcdefgi
So the stderr can be used for read?
I then close the stdout & stderr and make two copy of stdin:
int main(int argc, char** argv){
char buf[1024] = "abcdefghi\n";
close(1);
close(2);
dup2(0, 1);
dup2(0, 2);
write(0, buf, 10);
char redbuf[1024] = {0};
read(2, redbuf, 10);
write(2, redbuf, 10);
return 0;
}
Again it works.
output:
abcdefghi
hey stdin <-- I input this
hey stdin
So stdin can be used for write?
I need some explanation here.
Question
I want to know:
Why stdout/stderr can be used for read?
Why stdin can be used for write?
Is the three stream(stdin,stdout,stderr) internally one stream ?
If not, why am I getting this result?
/dev/null
, consider using the exit code from your program to pass one byte’s worth of status information back to the user (you). … (Cont’d)