Add Book to My BookshelfPurchase This Book Online

Chapter 6 - Special-Purpose File Operations

UNIX Systems Programming for SVR4
David A. Curry
 Copyright © 1996 O'Reilly & Associates, Inc.

The /dev/fd Filesystem
The /dev/fd filesystem allows each process to access its open file descriptors as names in the filesystem. If file descriptor n is open, the following two calls have the same effect:
    fd = open("/dev/fd/n", mode);
    fd = dup(n);
One of the most common uses for the /dev/fd filesystem is to “trick” programs that insist on reading from or writing to a file to read from the standard input or write to the standard output. For example, consider the following program:
    #include <stdio.h>
    #include <ctype.h>
    int
    main(int argc, char **argv)
    {
        int c;
        FILE *fp;
        if ((fp = fopen(*++argv, "r")) == NULL) {
            perror(*argv);
            exit(1);
        }
        while ((c = getc(fp)) != EOF) {
            if (islower(c))
                c = toupper(c);
            putc(c, stdout);
        }
        fclose(fp);
        exit(0);
    }
This program opens the file named on its command line, reads the file, and prints it out in uppercase. Unfortunately, since this program insists on reading from a file, it cannot be used as part of a pipeline to convert the output from another command to uppercase.
The /dev/fd filesystem remedies this by allowing the program's standard input to be specified as a filename. To use the above program in a pipeline then, we can do this:
    % somecommand | toupper /dev/fd/0
The /dev/fd filesystem was originally developed in Research UNIX. Shortly thereafter, public-domain implementations for BSD UNIX appeared, and it eventually appeared in SVR3. From there, it also became a part of SVR4. It is gradually appearing in other vendors' releases as well.
The /dev/fd filesystem is not available in HP-UX 10.x.

Previous SectionNext Section
Books24x7.com, Inc © 2000 –  Feedback