JMU
UNIX File Descriptors
An Introduction


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Review
Opening a File
Contents of the Tables
Relationships Between Tables
images/file-descriptors.gif
Relationships Between Tables (cont.)
Duplicating a File Descriptor: dup() dup
int dup(int oldfd);
Purpose:
Create a copy of a file descriptor using the lowest available number
Details:
oldfd The existing file descriptor
Return The new file descriptor; -1 on error
#include <unistd.h> unistd.h
Duplicating a File Descriptor: dup2() dup2
int dup2(int oldfd, int newfd);
Purpose:
Create a copy of a file descriptor
Details:
oldfd The existing file descriptor
newfd The new file descriptor (to silently close and re-) use
Return The new file descriptor; -1 on error
#include <unistd.h> unistd.h
Duplicating a File Descriptor: Some Values of errno

EBADF fd isn't a valid open file descriptor
EMFILE The per-process limit has been reached

An Example of the Relationships Between Tables
images/file-descriptors_example.gif
"Standard" File Descriptors
Closing a File
Finding Open File Descriptors
Using <stdio> with File Descriptors
Using <stdio>: fdopen() fdopen
FILE *fdopen(int fd, const char *mode)
Purpose:
Associate a FILE* (i.e., stream) with a valid file descriptor
Details:
fd The descriptor
mode "r", "w", "a", or "r+"/"w+" for read, write, append, read and write
Return A pointer to a stream or NULL
#include <stdio.h> stdio.h