#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) //模擬dup2的行爲,當filedes2等於filedes時,直接返回filedes便可
return filedes;
for(n=0 ; (fd=dup(filedes)) < filedes2; n++){ //因爲dup總返回當前可用文件描述符的最小值,所以要不斷嘗試
fd_rec[n] = fd; //保存嘗試的文件描述符,以便後面關閉
}
if( fd != filedes2) //退出循環的條件也可能因爲filedes2已被佔用,這時dup2先將原先佔有filedes2的文件關掉,此時dup確定是filedes2
{
close(filedes2);
fd = dup(filedes);
}
//關閉打開的非目標文件描述符
for(i=0; i<n; i++)
close(fd_rec[i]);
return fd;
}
對於my_dup2的測試,linux
$ my_dup2 2 17shell
將在屏幕上輸出"It works!";bash
$ my_dup2 7 17 7<>/dev/fd/1函數
也將輸出"It works!";測試
$ my_dup2 2 17 17>tmp.fooui
屏幕輸出"It words!",但tmp.foo中沒有任何記錄,這個例子模擬17已被佔有的情形。it