Chapter Contents

Previous

Next
dup

dup



Duplicate File Descriptor

Portability: POSIX.1 conforming, UNIX compatible


SYNOPSIS
DESCRIPTION
RETURN VALUE
EXAMPLE
RELATED FUNCTIONS
SEE ALSO


SYNOPSIS

#include <unistd.h>

int dup(int filedes);


DESCRIPTION

dup duplicates an USS file descriptor to the lowest numbered available file descriptor. filedes is the original file descriptor. The new descriptor has the same file position as the original file descriptor and shares any record locks.


RETURN VALUE

dup returns a file descriptor if successful and it returns a -1 if it is not successful.


EXAMPLE

This example invokes the shell command tr to translate a file to lowercase and copy it to stdout . The filename is specified on the command line. The dup function assigns the file to standard input before using execlp to invoke the tr command. This example should be compiled with the posix option and run under the USS shell:

#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>

main(int argc, char *argv[]) {
   int input;
   int newfd;
      /* If no argument, input is stdin.             */
   if (argc > 1) {
      input = open(argv[1], O_RDONLY);
      if (input < 0) {
         perror("open error");
         exit(EXIT_FAILURE);
      }
         /* If input is already fd 0, no dup needed. */
      if (input != STDIN_FILENO) {
            /* Close standard input. */
         close(STDIN_FILENO);
            /* Duplicate to lowest avail fd (0).     */
         newfd = dup(input);
         if (newfd != 0) {    /* should not occur    */
            fputs("Unexpected dup error.\n", stderr);
            exit(EXIT_FAILURE);
         }
           /* Close original fd. */
         close(input);
      }
   }
   execlp("tr", "tr", "[:upper:]", "[:lower:]");
   perror("exec error");  /* exec must have failed.  */
   exit(EXIT_FAILURE);
}


RELATED FUNCTIONS

dup2 , fcntl


SEE ALSO


Chapter Contents

Previous

Next

Top of Page

Copyright © 2001 by SAS Institute Inc., Cary, NC, USA. All rights reserved.