Chapter Contents

Previous

Next
dup2

dup2



Specify Duplicate File Descriptor

Portability: POSIX.1 conforming, UNIX compatible


SYNOPSIS
DESCRIPTION
RETURN VALUE
EXAMPLE
RELATED FUNCTIONS
SEE ALSO


SYNOPSIS

#include <unistd.h>

int dup2(int fd1, int fd2);


DESCRIPTION

dup2 returns a file descriptor with the value of fd2 . The fd2 function refers to the same file as fd1 . If fd2 is an open file descriptor and does not equal fd1 , fd2 is closed before it is duplicated. fd1 must be the file number of an open HFS file.


RETURN VALUE

dup2 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 dup2 function assigns the file to standard input before using execlp to invoke the tr command. This example has the same purpose as the dup example but is less complicated due to the use of dup2 . 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);
      }
         /* sup input to standard input             */
      newfd = dup2(input, STDIN_FILENO);
      if (newfd < 0) {
         perror("dup2 error");
         exit(EXIT_FAILURE);
      }
         /* Close original fd.                      */
      if (newfd != input) {
         close(input);
      }
   }
   execlp("tr", "tr", "[:upper:]", "[:lower:]");
   perror("exec error");  /* exec must have failed. */
   exit(EXIT_FAILURE);
}


RELATED FUNCTIONS

dup , fcntl


SEE ALSO


Chapter Contents

Previous

Next

Top of Page

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