Sunday, August 28, 2011

Understanding the Need for Standard I/O in socket


Why standard I/O is required in socket

The stdio(3) facility in Linux conforms to the ANSI C3.159-1989 standard. This standardization of the interface helps programs to be portable to many platforms. This might be useful to you, when
porting source code from other UNIX systems to your own Linux platform, for example.

The stdio(3) package will itself issue read(2) and write(2) calls, "under the hood," so to speak. You, however, use the standard I/O calls instead, because they will offer you the convenience of getting a line or character at a time, according to your application needs. The read(2) call, for example, cannot return to your application one text line. Instead, it will return as much data as it can, even multiple text lines.

When writing to the socket, the standard I/O routines allow your application to write characters out one at a time, for example, without incurring large overhead. On the other hand, calling write(2) to write one character at a time is much more costly. The standard I/O functions permit your application to work with convenient units of data.

The stdio(3) package also provides the capability to buffer your data, both for input and for output. When buffering can be used, it can significantly improve the I/O performance of your application. Unfortunately, buffering creates difficulties for some forms of communication, and so it cannot always be used.

It will be assumed in this text that you are already familiar with the basics of stdio(3). This is usually taught in C programming texts, along with the C language itself. Consequently, this text will focus on things you need to watch out for, and other subtleties that might not be obvious, as it applies to socket programming.

NOTE
Linux introduces the standard I/O routines in its stdio(3) man page. Perform the following command to display this introductory text:

[sgupta@rhel55x86 using-I_O-on-socket]$ man 3 stdio

This will provide a list of standard I/O functions. If  these all seem new to you, then you might want to review some of them. You should be acquainted with at least fopen(3), fread(3), fgets(3), fwrite(3), fflush(3), and fclose(3).

1 comment: