Skip to content

Instantly share code, notes, and snippets.

@keith-bennett-gbg
Last active November 17, 2017 16:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keith-bennett-gbg/6fe80134ac8f61dcf2cc72ea45c0d4e8 to your computer and use it in GitHub Desktop.
Save keith-bennett-gbg/6fe80134ac8f61dcf2cc72ea45c0d4e8 to your computer and use it in GitHub Desktop.
struct file_descriptor
{
// implementation goes here
int read(char * destination, int count);
int write(char * source, int count);
};
struct disk_file : public file_descriptor
{
// route requests to disk I/O functions
int read(char * destination, int count);
int write(char * source, int count);
}
struct socket_file : public file_descriptor
{
// route requests to network I/O functions
int read(char * destination, int count);
int write(char * source, int count);
}
// kernel keeps record of the list of file descriptors you have open
int file_descriptor_count = /* some value meaning the maximum number of open files you are permitted to have */
file_descriptor * descriptors = malloc(file_descriptor, sizeof(file_descriptor) * file_descriptor_count;
// read() will read `count` bytes from the _file descriptor_ and put into `destination`.
// it will return the number of bytes which were successfully read (which may be different from the count you requested
// or it will set errno to an appropriate _error reason_ and return -1 if an error occurred.
int read(int fd_value, char * destination, int count)
{
if ( (fd_value < 0) || (file_descriptor_count <= fd_value)|| (nullptr == destination) )
{
errno = /* something from #include <errno.h> which meands you gave bad function arguments */
return -1;
}
// hand the request off to the file descriptor
return descriptors[fd_value].read(destination, count);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment