dup2的实现

APUE第三章的一个习题,分享一下

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <fcntl.h>
 4 #include <unistd.h>
 5 #include <errno.h>
 6 
 7 #define FILE_MODE   (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
 8 
 9 int mydup2 (int oldfile, int newfile) {
10   int tempfile;
11   if ((tempfile = dup(oldfile)) < 0) {
12     perror("dup(oldfile)");
13     printf("strerror:%s\n", strerror(errno));
14   } else {
15     close(tempfile);
16   }
17   close(newfile);
18   int tempfiles[newfile];
19   int i;
20   for(i = 0; i < newfile; ++i) {
21     if ((tempfile = dup(oldfile)) != newfile) {
22       tempfiles[i] = tempfile;
23     } else {
24       break;
25     }
26   }
27   while(i > 0) {
28     close(tempfiles[i--]);
29   }
30   return tempfile;
31 }
32 int main(int argc, char const *argv[])
33 {
34   int fd = open("mydup2.file", O_RDWR | O_CREAT | O_TRUNC, FILE_MODE);
35   int newfd = mydup2(fd, 20);
36   printf("fd: %d\nnewfd: %d\n", fd, newfd);
37   char wstr[] = "mydup2 test file\n";
38   pwrite(newfd, wstr, sizeof(wstr), 0);
39   char rstr[sizeof(wstr)];
40   pread(fd, rstr, sizeof(wstr), 0);
41   printf("%s\n", rstr); 
42   return 0;
43 }
posted @ 2012-10-03 16:51  khalil  阅读(229)  评论(0编辑  收藏  举报