Streams
Depends on | Queues • Shell |
---|
A ‘stream’ is a serial flow of data. It is not the same as a file – files can be addressed in a ‘random’ manner – but files are not infrequently read or written as serial streams. Indeed it is often said of Unix-family operating systems that “everything is a file”.
In this case, the stream is an unstructured, serial succession of bytes. Input from the stream will give the next byte – if and when there is one – and the byte is removed from the input sequence in the process. Output to a stream will output – assuming no ‘back-pressure’ from something (such as writing a file) being slow further downstream; again the byte is then ‘gone’.
I/O devices can also be treated as streams. Your keyboard provides an input stream, for example.
Unix Standard Streams
All Unix processes are provided with three standard streams:
- Standard input (
stdin
) – usually defaults to keyboard. - Standard output (
stdout
) – usually defaults to display. - Standard error (
stderr
) – usually also defaults to display.
Processes can ‘get’ and ‘put’ characters to these streams in various ways. They are typically the default source/sink of input/output in system applications. You should be quite used to using them by now!
Redirection
Unix can redirect a stream to a file or, via a pipe, to another process. From a Unix command line try something like:
ls | wc > clutter
That example redirects the stdout
from the ls
process to the stdin
of wc
, and wc
's stdout
to a file. This sort of thing is often jolly useful!
Streams as files
Standard streams can often be both implicit or explicit when programming.
Example
The C statement:
printf("Hello World!\n");
can also be written as:
fprintf(stdout, "Hello World!\n");
in a similar way to ‘printing’ to a file:
fprintf(file_handle, "Hello World!\n");