This preview shows page 1. Sign up to view the full content.
Unformatted text preview: ion to read a ﬁle:
1 2 if (S_ISREG(stat.st_mode) && (stat.st_mode & S_IRUSR)) printf("This is a regular file that I can read\n"); 12.4.5 The dup2 Function
The Unix shell provides an I/O redirection operator that allows users to redirect the standard output to a disk ﬁle. For example,
unix> ls >foo writes the standard output of the ls program to the ﬁle foo. As we shall see in Section 12.7, a Web server performs a similar kind of redirection when it runs a CGI program on behalf of the client. One way to accomplish I/O redirection is to use the dup2 function.
#include <unistd.h> int dup2(int oldfd, int newfd);
returns: nonnegative descriptor if OK, -1 on error The dup2 function duplicates descriptor oldfd, assigns it to descriptor newfd, and returns newfd. If newfd was already open, then dup2 closes newfd before it duplicates oldfd. For each process, the kernel maintains a descriptor table that is indexed by the process’s open descriptors. The entry for an open descriptor points to a ﬁle table entry that consists of, among other thin...
View Full Document