int mydup2(int oldfd, int newfd)
{
int tfd = 0;
if (newfd < 0)
{
err_sys("newfd < 0");
}
if (newfd == oldfd)
return oldfd;
while(1)
tfd = dup(oldfd);
if (tfd == newfd)
{
return newfd;
}
else if (tfd > newfd)
close(newfd);
}
测试:
#include "apue.h"
#include <fcntl.h>
int mydup2(int oldfd, int newfd);
int main(void)
int fd = 0;
fd = open("testdup2.dat", O_RDWR | O_CREAT | O_TRUNC);
if (fd < 0)
printf("open error.\n");
return -1;
if (mydup2(fd, STDOUT_FILENO) < 0)
printf("mydup2 error\n");
printf("slk\n");
return 0;
可以把输出重定向到testdup2.dat,成功