- #include <stdio.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <error.h>
- #include <ctype.h>
- #include <unistd.h>
- int dup2_same(int,int);
- int main(int argc,char *argv[])
- {
- int fd,fd2;
- char buf[10];
- if((fd=open("mydup.file",O_RDWR|O_CREAT|O_TRUNC, S_IRUSR | S_IWUSR | S_IXUSR))==-1)
- {
- perror("Can't open");
- return 0;
- }
- if(argc!=2)
- {
- printf("ERROR\\n");
- return 0;
- }
- fd2=atoi(argv[1]);
- dup2_same(fd,fd2);
- if(write(fd2,"Hello\\n",6)==-1)
- {
- perror("write fail");
- return -1;
- }
- lseek(fd2,0,SEEK_SET);
- read(fd2,buf,5);
- puts(buf);
- return 0;
- close(fd);
- close(fd2);
- }
- int dup2_same(int fd,int fd2)
- {
- int a[fd2],temp,i=0;
- if(fd==fd2)
- return fd;
- close(fd2);
- while(temp=dup(fd))
- {
- if(fd2=temp)
- break;
- else
- a[i++] = temp;
- }
- for(;i>0;i--)
- close(a[i-0]);
- return fd2;
- }
- //该片段来自于http://www.codesnippet.cn/detail/301220138331.html
来源: http://www.codesnippet.cn/detail/301220138331.html