The requirement of exercise 3.2 is to write a function with the same dup2 () function without using fcntl (). It is intuitive to constantly use the DUP () until the specified file descriptor is returned.
#include <stdio.h>
#include <stdlib.h>
#define OPEN_MAX 63
int my_dup2 (int filedes,int filedes2);
Int
Main (int argc, char* argv[])
{
int fd,fd2;
Char buf[] = "It work!\n";
if (argc! = 3)
Err_quit ("Usage:%s <filedes#> <filedes2#>", argv[0]);
FD = Atoi (argv[1]);
FD2 = Atoi (argv[2]);
My_dup2 (FD, FD2);
printf ("fd#%d-fd#%d\n", FD2, FD);
if (Write (FD2, buf, 9)! = 9)
Err_sys ("write error");
Exit (0);
}
Int
my_dup2 (int filedes,int filedes2)
{
int Fd_rec[open_max];
int fd,i,n;
if (filedes = = filedes2)//Analog dup2 behavior, when Filedes2 equals Filedes, return directly to Filedes
return filedes;
for (n=0; (Fd=dup (Filedes)) < Filedes2; n++) {//Because dup2 always returns the minimum value of the currently available file descriptor, try to keep trying
Fd_rec[n] = FD; Save the attempted file descriptor so that it is closed later
}
If the condition of the IF (fd! = filedes2)//exit loop may also be due to filedes2 already occupied, then Dup2 's behavior is to first close it
{
Close (Filedes2);
FD = DUP (filedes);
}
Close open non-target file descriptor
for (i=0; i<n; i++)
Close (Fd_rec[i]);
return FD;
}
The input and output redirection symbols for commands are often used in the Linux bash shell. For example, the use of program 3-4 in "Apue" $ a.out </dev/tty//redirect program input to/dev/tty $ a.out > Tmp.foo//redirect program output to file Temp.foo $ a.out 2>> temp.foo//on File descriptor 2 Open File Temp.foo for add-on, usually when a program error writes the relevant error message to FD#2 $ a.out 5<&G T;temp.foo//fd#5 Open file Temp.foo for read, write file descriptor there are usually several values that are reserved for use by the system, by default, 0-standard input, 1-standard output, and 2-error output.
- In the absence of these redirection symbols, the shell initializes the fd#0, Fd#1, and fd#3 points during the preparation phase before running the command program.
- When using a redirect, the task of opening the file on the specified file descriptor is also done in the preparation phase before the shell runs the command program.
For the my_dup2 test,
$ my_dup2 2 17
The "It works!" will be output on the screen ;
$ my_dup2 7 7<>/DEV/FD/1
will also output "It works!";
$ my_dup2 2 17>tmp.foo
The screen outputs "It words!", but there are no records in Tmp.foo.
Apue Exercise 3.2 and the use of redirect symbols in the shell