#include <unistd.h> int dup2(int fd1, int fd2);
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.
dup2
returns a file descriptor if successful and it returns a - 1
if it is not successful.
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 OpenEdition 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); }
dup
, fcntl
Copyright (c) 1998 SAS Institute Inc. Cary, NC, USA. All rights reserved.