函数dup与dup2

函数原型

1
2
3
4
#include <unistd.h>
int dup(int fd);
int dup2(int fd, int fd2);

函数功能

这两个函数的功能都是用来复制一个现有的文件描述符。返回的文件描述符与原有的文件描述符共用同一个文件表项,但是文件描述符标志将被清除,即当进程调用exec时文件描述符将不会被关闭。

返回值

dup返回当前可用的最小的文件描述符。dup2返回fd2,若fd2所表示的文件已经打开,则将该文件描述符先关闭,然后再将fd复制到fd2上返回。若fd2与fd相同,则直接返回fd、.

等效函数

dup函数与fcntl的F_DUPFD功能相同。

dup(fd)等效于fcntl(fd, F_DUPFD, 0)

dup2(fd, fd2)等效于close(fd), fcntl(fd, F_DUPFD, fd2)

但是dup2是原子的上述先关闭然后在复制不是原子操作。

作用及用途

dup函数常用来重定向进程的stdin、stdout以及stderr。原理与CGI类似,即将标准输入标准输出重定向到一个文件或者socket流等。

重定向标准输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/types.h>
#include <stdio.h>
int main() {
int fd = dup(STDIN_FILENO);
if (fd < 0) {
printf("dup error\n");
exit(1);
}
char buf[] = "this is a test of dup\n";
write(fd, buf, sizeof(buf));
return 0;
}

Comment and share

  • page 1 of 1

魏传柳(2824759538@qq.com)

author.bio


Tencent


ShenZhen,China