Write your own dup2 function that performs the same service as the dup2 function described in Section 3.12, without calling the fcntl function. Be sure to handle errors correctly.(实现自己的dup2函数,不能使用fcntl函数,注意处理错误值。)
函数原型
int dup2(int filedes, int filedes2);
函数功能
makes filedes2 be the copy of filedes, closing newfd first if necessary.(复制filedes到filedes2,若filedes2打开,则先关闭)
思路
要判断filedes2是否存在,可以使用dup函数,判断返回值。若ok或者,返回-1时的错误值不为EBADF,则表明filedes2是打开的。
1 //程序功能:仿照dup4的功能
2 #include <stdio.h>
3 #include <string.h>
4 #include <unistd.h>
5 #include <fcntl.h>
6 #include <errno.h>
7 #include <stdlib.h>
8
9 #define BUFFSIZE 4096
10
11 int my_dup2 (int fd1, int fd2) {
12 int tmpfd = -1, lastfd, i;
13 int * fds = NULL;
14 if (fd2 < 0
15 #ifdef OPEN_MAX
16 || fd2 > OPEN_MAX
17 #endif
18 ) {
19 errno = EBADF;
20 printf ("my_dup2 %d, is not avlid number.\n", __LINE__);
21 return -1;
22 }
23 tmpfd = dup (fd2);//判断fd2是否已经打开
24 if (tmpfd == -1) {
25 switch (errno) {
26 case EBADF:
27 printf ("my_dup2 %d, fd2 is not opened.\n", __LINE__);//fd2 is not opened.
28 break;
29
30 case EMFILE:
31 if (close (fd2) == -1) {
32 printf ("my_dup2 %d, closed failed.\n", __LINE__);
33 return -1;
34 }
35 break;
36
37 default:
38 printf ("my_dup2 %d, dup fd2 failed.\n", __LINE__);
39 return -1;
40 }
41 }
42 else {
43 if (close (tmpfd) < 0) {
44 printf ("my_dup2 %d, closed tmpfd failed.\n", __LINE__);
45 return -1;
46 }
47 if (close (fd2) < 0) {
48 printf ("my_dup2 %d, closed fd2 failed.\n", __LINE__);
49 return -1;
50 }
51 }
52
53 fds = (int*)malloc (fd2*sizeof (int));
54 if (!fds) {
55 printf ("my_dup2 %d, malloc fds failed.\n", __LINE__);
56 errno = ENOMEM;
57 return -1;
58 }
59
60 for (i = 0; i < fd2 ; ++i)
61 fds[i] = -1;
62 lastfd = -1;
63 while (tmpfd = dup(fd1)) {
64 printf ("tmpfd = %d\n", tmpfd);
65 if (tmpfd == -1) {
66 printf ("my_dup2 %d, dup fd1 failed.\n", __LINE__);
67 goto FAILED_EXIT;;
68 }
69 else if (tmpfd == fd2)
70 break;
71 else {
72 fds[tmpfd] = tmpfd;
73 lastfd = tmpfd;
74 }
75 }
76
77 for (i = 0; i < fd2; ++i) {
78 if (fds[i] != -1) close (fds[i]);
79 }
80 free (fds);
81 return fd2;
82
83 FAILED_EXIT:
84 for (i = 0; i < fd2; ++i) {
85 if (fds[i] != -1) close (fds[i]);
86 }
87 free (fds);
88 return -1;
89 }
91 int main (int args, char* argv[]) {
92 int fd;
93 if (args != 3) {
94 printf ("Usage: ./a.out <fdnumber> <fdcontent>\n");
95 return -1;
96 }
97 if ((fd = open ("file1", O_RDWR)) < 0)
98 perror ("open");
99 int fd3 = my_dup2 (fd, atoi (argv[1]));
100 printf ("%d %d\n", fd, fd3);
101 //char* Dstr = "my_dup2\n";
102 int val = write (fd3, /*Dstr*/argv[2], strlen (/*Dstr*/argv[2]) + 1);
103 printf ("[第%d行] val = %d, %d\n", __LINE__, val, (int)strlen (argv[2]));
104 char buf[BUFFSIZE] = {};
105 lseek (fd3, 0, SEEK_SET);
106 if (read (fd3, buf, val) < 0)
107 perror ("read");
108 printf ("wrote \"%s\" in the file1.\n", buf);
109 close (fd);
110 return 0;
111 }
1,28-21 顶端