STREAMS Programming Guide

Exit Print View

Updated: July 2014
 
 

Simple Stream Example

Example 1–1 shows how an application might use a simple stream. Here, the user program interacts with a communications device that provides point-to-point data transfer between two computers. Data written to the device is transmitted over the communications line, and data arriving on the line is retrieved by reading from the device.

Example 1-1  Simple Stream
#include <sys/fcntl.h>
#include <stdio.h>

main()
{
		char buf[1024];
		int fd, count;
	
		if ((fd = open("/dev/ttya", O_RDWR)) < 0) {
			perror("open failed");
			exit(1);
		}
		while ((count = read(fd, buf, sizeof(buf))) > 0) {
			if (write(fd, buf, count) != count) {
				perror("write failed");
				break;
			}
		}
		exit(0);
}

In this example, /dev/ttya identifies an instance of a serial communications device driver. When this file is opened, the system recognizes the device as a STREAMS device and connects a stream to the driver. Figure 1–3 shows the state of the stream following the call to open(2).

Figure 1-3  Stream to Communications Driver

image:Diagram shows the state of the stream in the Simple Stream example after a call to open.

This example illustrates a simple loop, with the application reading data from the communications device, then writing the input back to the same device, echoing all input back over the communications line. The program reads up to 1024 bytes at a time, and then writes the number of bytes just read.

read(2) returns the available data, which can contain fewer than 1024 bytes. If no data is currently available at the stream head, read(2) blocks until data arrives.


Note - The application program must loop on read(2) until the desired number of bytes are read. The responsibility for the application getting all the bytes it needs is that of the application developer, not the STREAMS facilities.

Similarly, the write(2) call attempts to send the specified number of bytes to /dev/ttya. The driver can implement a flow-control mechanism that prevents a user from exhausting system resources by flooding a device driver with data.