#include <unistd.h> int dup(int filedes);
dup
duplicates an OpenEdition 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.
dup
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 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
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); } /* 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); }
dup2
, fcntl
Copyright (c) 1998 SAS Institute Inc. Cary, NC, USA. All rights reserved.