Linux/Unix系统编程手册 5-5 .编写一程序,验证文件描述符及其副本是否共享了文件偏移量和打开文件的状态标志。
设原文件描述符fd,副本文件描述符cpfd,先用lseek获取两个文件描述符指向的文件的文件偏移量,然后与调用write后的文件偏移量作比较可得出共享了文件偏移量的结论,在之后调用fcntl加入O_APPEND这一原来没有打开的状态,和上面一样比较两个描述符打开的文件的状态也可得共享打开文件的状态标志的结论。
#include<fcntl.h>
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
int main()
{
int fd,cpfd;
off_t seek;
int flags;
fd = open("test",O_CREAT | O_RDWR,S_IRUSR | S_IWUSR);
if(fd == -1) {
perror("open fail");
exit(1);
}
cpfd = dup(fd);
if(cpfd == -1) {
perror("dup fail");
exit(1);
}
seek = lseek(fd,0,SEEK_CUR);
if(seek == -1) {
perror("lseek fd fail");
exit(1);
} else
printf("the old fd_seek is: %ld\n",seek);
lseek(cpfd,0,SEEK_CUR);
if(seek == -1) {
perror("lseek fd fail");
exit(1);
} else
printf("the old cpfd_seek is: %ld\n",seek);
if(write(fd,"test",4) == -1) {
perror("write fail");
exit(1);
}
seek = lseek(fd,0,SEEK_CUR);
if(seek == -1) {
perror("lseek fd fail");
exit(1);
} else
printf("the new fd_seek is: %ld\n",seek);
seek = lseek(cpfd,0,SEEK_CUR);
if(seek == -1) {
perror("lseek fd fail");
exit(1);
} else
printf("the new cpfd_seek is: %ld\n",seek);
flags = fcntl(fd,F_GETFL);
if(flags == -1) {
perror("fcntl fail");
exit(1);
}
flags |= O_APPEND;
flags = fcntl(fd,F_SETFL,flags);
if(flags == -1) {
perror("fcntl fail");
exit(1);
}
flags = fcntl(fd,F_GETFL);
if(flags == -1) {
perror("fcntl fail");
exit(1);
}
if((flags&O_APPEND) == O_APPEND)
printf("fd's mode has O_APPEND\n");
flags = fcntl(cpfd,F_GETFL);
if(flags == -1) {
perror("fcntl fail");
exit(1);
}
if((flags&O_APPEND) == O_APPEND)
printf("cpfd's mode has O_APPEND\n");
}
输出如下: