Monday, November 10, 2008

Writing to stdin

Remember, stdin is file descriptor 0.

#include <stdio.h>
#include <string.h>

int main(void)
{
char *output = "Hello, Stdin World!\n";

write(0, output, strlen(output));
return 0;
}


[prompt]$ gcc -o stdin-write stdin-write.c
[prompt]$ ./stdin-write 1>/dev/null 2>/dev/null
Hello, Stdin World!
[prompt]$

So you can write to stdin because it is opened Read/Write on linux. Probably also on other platforms as well. std{in,out,err} are just conventions for the names and uses of file descriptors 0, 1, and 2, and there is no technical restriction in place on them. Still, writing to stdin is unusual and unexpected.