函数原型:
#include <unistd.h>
int dup2(int oldfd, int newfd);
函数功能描述:
将描述符newfd重定向到oldfd
下面是一个demon,将文件a.txt的描述符重定向到标准输出STDIN_FILENO:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int fd, refd;
char buf[1024] = "hello\n";
fd = open("a.txt", O_RDWR|O_CREAT, 0644);
if (fd == -1)
{
printf("open file error!\n");
exit(-1);
}
refd = dup2(STDIN_FILENO, fd);
if (refd == -1)
{
printf("dup2 error!\n");
exit(-1);
}
write(fd, buf, strlen(buf));
close(fd);
return 0;
}
运行结果:
hello