#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
int main()
{
char buf[20] = "duptest";
int fd1, fd2, i;
fd1 = open("test", O_RDWR | O_CREAT | O_TRUNC, 0666); //打开文件ftest
if (fd1 < 0) {
printf("error: ftest open\n");
return -1;
}
fd2 = dup(fd1); //复制fd1
if (fd2 < 0) {
printf("error: dup\n");
close(fd1);
return -1;
}
for (i = 0; i < 7; i++) { //循环7次,写入duptest
if ( write(fd1, &buf, 1) < 0 ) { //先向fd1写入
printf("error: fd1 write, i=%d\n", i);
close(fd1);
close(fd2);
return -1;
}
if ( write(fd2, &buf, 1) < 0 ) { //再向fd2写入
printf("error: fd2 write, i=%d\n", i);
close(fd1);
close(fd2);
return -1;
}
}
if (lseek(fd1, 0, SEEK_SET) < 0) { //将位置指针设置到文件开头
printf("error: fd1 lseek\n");
close(fd1);
close(fd2);
return -1;
}
if (read(fd1, buf, 14) < 0) { //读取文件内容
printf("error: fd1 read\n");
close(fd1);
close(fd2);
return -1;
}
printf("fd1=%d,fd2=%d,dup test:%s\n", fd1, fd2, buf);
close(fd1);
close(fd2);
return 0;
}