Tuesday, September 20, 2011

I/O on socket pair


Performing I/O on Sockets

sockets can be written to and read from just like any opened file. In this section, you are going to demonstrate this firsthand for yourself. For the sake of completeness however, let's review the function synopsis for the calls read(2), write(2), and close(2) before we put them to work:

#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
ssize_t write(int fd, const void *buf, size_t count);
int close(int fd);

These are Linux input/output functions you should be already familiar with. By way of review, the function read(2) returns input that is available from the file descriptor fd, into your supplied buffer buf of a maximum size of count bytes. The return value represents the number of bytes read. A return count of zero represents end-of-file.

The write(2) function writes data to your file descriptor fd, from your supplied buffer buf for a total of count bytes. The returned value represents the actual number of bytes written. Normally, this should match the supplied count argument.

However, there are some valid circumstances where this will be less than count, but you won't have to worry about it here.

Finally, close(2) returns zero if the unit was closed successfully. A return value of -1 for any of these functions indicates that an error occurred, and that the reason for the error is posted to the external variable errno. To make this value accessible, include the file errno.h within the source module that needs it.

Example

No comments:

Post a Comment