请人做网站得多少钱,wordpress comments,网站推广建设加盟,传奇网页游戏破解版#include unistd.h
int dup(int oldfd);
int dup2(int oldfd, int newfd);
作用#xff1a;dup函数实现对一个文件的文件描述符进行复制#xff0c;复制之后该进程就会新增加一一个文件描述符指向该文件#xff08;即实现同一个文件对应多个文件描述符#xff0…#include unistd.h
int dup(int oldfd);
int dup2(int oldfd, int newfd);
作用dup函数实现对一个文件的文件描述符进行复制复制之后该进程就会新增加一一个文件描述符指向该文件即实现同一个文件对应多个文件描述符。dup2函数如果new是一个被打开的文件描述符与old不是同一个文件则在拷贝前先关闭newnew就不需要占据那个文件描述符了即使new文件的文件描述符重新指向old文件如果两个文件描述符对应的是同一个文件则直接返回文件描述符。 文件描述符的复制又称为文件描述符的重定向。
dup返回值返回新的文件描述符文件描述符表中最小的未被占用的文件描述符。 出错返回-1。
dup2返回值如果两个文件描述符对应的是同一个文件则直接返回文件描述符。不拷贝。如果不是同一个文件则返回new的那个文件描述符。出错 返回-1。
//dup函数代码
#include stdio.h
#include stdlib.h
#include string.h
#include unistd.h
#include sys/types.h
#include sys/stat.h
#include fcntl.hint main()
{int fd open(a.txt, O_RDWR); //文件第一次被打开时其文件指针置于文件首部if(fd -1){perror(open);exit(1);}printf(file open fd %d\n, fd);int ret dup(fd); //文件描述符的复制重定向if(ret -1){perror(dup);exit(1);}printf(dup fd %d\n, ret);char* buf 你是猴子派来的救兵吗\n;char* buf1 你大爷的我是程序猿\n;write(fd, buf, strlen(buf)); //通过fd来向文件写入数据write(ret, buf1, strlen(buf1)); //通过ret来向同一文件继续写入数据注意是追加写入因为一个文件的文件读写指针只有一个因此第一个文件操作后第二个接着第一个的位置继续进行。close(fd); //此时只是释放了fd但还是可以通过ret来使用该文件。close(ret); //释放retreturn 0;
}//dup2函数代码
#include stdio.h
#include stdlib.h
#include string.h
#include unistd.h
#include sys/types.h
#include sys/stat.h
#include fcntl.hint main( )
{int fd open(english.txt, O_RDWR);if(fd -1){perror(open);exit(1);}int fd1 open(a.txt, O_RDWR);if(fd1 -1){perror(open);exit(1);}printf(fd %d\n, fd);printf(fd1 %d\n, fd1);int ret dup2(fd1, fd); //此时先关闭fd然后再将fd分配给a.txtif(ret -1){perror(dup2);exit(1);}printf(current fd %d\n, ret);char* buf 主要看气质 ^_^\n;write(fd, buf, strlen(buf));write(fd1, hello, world!, 13);close(fd);close(fd1);return 0;
}
[rootlocalhost dup]# ./dup2
fd 3
fd1 4
current fd 3