dup、dup2函數(15)

dup、dup2函數(15)

 

 代碼:

 1 /*
 2     #include <unistd.h>
 3     int dup(int oldfd);
 4         作用:複製一個新的文件描述符
 5         fd=3, int fd1 = dup(fd),
 6         fd指向的是a.txt, fd1也是指向a.txt
 7         從空閒的文件描述符表中找一個最小的,作爲新的拷貝的文件描述符
 8 
 9 
10 */
11 
12 #include <unistd.h>
13 #include <stdio.h>
14 #include <fcntl.h>
15 #include <sys/types.h>
16 #include <sys/stat.h>
17 #include <string.h>
18 
19 int main() {
20 
21     int fd = open("a.txt", O_RDWR | O_CREAT, 0664);
22 
23     int fd1 = dup(fd);
24 
25     if(fd1 == -1) {
26         perror("dup");
27         return -1;
28     }
29 
30     printf("fd : %d , fd1 : %d\n", fd, fd1);
31 
32     close(fd);
33 
34     char * str = "hello,world";
35     int ret = write(fd1, str, strlen(str));
36     if(ret == -1) {
37         perror("write");
38         return -1;
39     }
40 
41     close(fd1);
42 
43     return 0;
44 }

 

 1 /*
 2     #include <unistd.h>
 3     int dup2(int oldfd, int newfd);
 4         作用:重定向文件描述符
 5         oldfd 指向 a.txt, newfd 指向 b.txt
 6         調用函數成功後:newfd 和 b.txt 做close, newfd 指向了 a.txt
 7         oldfd 必須是一個有效的文件描述符
 8         oldfd和newfd值相同,相當於什麼都沒有做
 9 */
10 #include <unistd.h>
11 #include <stdio.h>
12 #include <string.h>
13 #include <sys/stat.h>
14 #include <sys/types.h>
15 #include <fcntl.h>
16 
17 int main() {
18 
19     int fd = open("1.txt", O_RDWR | O_CREAT, 0664);
20     if(fd == -1) {
21         perror("open");
22         return -1;
23     }
24 
25     int fd1 = open("2.txt", O_RDWR | O_CREAT, 0664);
26     if(fd1 == -1) {
27         perror("open");
28         return -1;
29     }
30 
31     printf("fd : %d, fd1 : %d\n", fd, fd1);
32 
33     int fd2 = dup2(fd, fd1);
34     if(fd2 == -1) {
35         perror("dup2");
36         return -1;
37     }
38 
39     // 通過fd1去寫數據,實際操作的是1.txt,而不是2.txt
40     char * str = "hello, dup2";
41     int len = write(fd1, str, strlen(str));
42 
43     if(len == -1) {
44         perror("write");
45         return -1;
46     }
47 
48     printf("fd : %d, fd1 : %d, fd2 : %d\n", fd, fd1, fd2);
49 
50     close(fd);
51     close(fd1);
52 
53     return 0;
54 }

 

 

 

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章