dup(int filedes)函数返回一个可用的与filedes共享文件表项的最小描述符。
而dup2(int filedes,int filedes2)是使用一个描述符filedes2去指向filedes2文件表项(也是共享),但是在调用dup2之前要确保filedes2为可用描述符。
例如在rethat下测试:
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
int sharefd,fd;
char buf[100];
int n;
fd = open("./long.txt",O_RDWR);
sharefd = dup(fd);
printf("share:%d,fd:%d\n",sharefd,fd);
close(fd);
if( (n = read(sharefd,buf,100))<0)
{
return -1;
}
buf[n] = '\0';
printf("Read :%s\n",buf);
}
运行结果:
[root@localhost ipc]# ./a.out
share:4,fd:3
Read :Hello world
如果把上面代码的sharefd = dup(fd)改为dup2(fd,sharefd),
运行结果:
[root@localhost ipc]# ./a.out
share:-1081367928,fd:3
原因就是我们的sharefd描述符是随机数,不可用描述符,所以不能使用dup2函数。
额外:可以加判断避免这种错误:
if(dup2(fd,sharefd)! =sharefd )
exit(0);