fcntl是計(jì)算機(jī)中的一種函數(shù),通過fcntl可以改變已打開的文件性質(zhì)。fcntl針對描述符提供控制。參數(shù)fd是被參數(shù)cmd操作的描述符。針對cmd的值,fcntl能夠接受第三個(gè)參數(shù)int arg。
fcntl的返回值與命令有關(guān)。如果出錯(cuò),所有命令都返回-1,如果成功則返回某個(gè)其他值。
定義函數(shù)
?int fcntl (int fd, int cmd);?
int fcntl (int fd, int cmd, long arg);?
int fcntl (int fd, int cmd, struct flock *lock);
fcntl()針對(文件)描述符提供控制.參數(shù)fd 是被參數(shù)cmd操作(如下面的描述)的描述符.
針對cmd的值,fcntl能夠接受第三個(gè)參數(shù)int arg
fcntl即F_SETFL,F_GETFL的使用,設(shè)置文件的flags,阻塞設(shè)置成非阻塞,非阻塞設(shè)置成阻塞(這連個(gè)在開發(fā)中可以封裝為基本函數(shù))
1、獲取文件的flags,即open函數(shù)的第二個(gè)參數(shù):
?????? flags = fcntl(fd,F_GETFL,0);
2、設(shè)置文件的flags:
??????fcntl(fd,F_SETFL,flags);
3、增加文件的某個(gè)flags,比如文件是阻塞的,想設(shè)置成非阻塞:
?????? flags = fcntl(fd,F_GETFL,0);
?????? flags |= O_NONBLOCK;
??????fcntl(fd,F_SETFL,flags);
4、取消文件的某個(gè)flags,比如文件是非阻塞的,想設(shè)置成為阻塞:
??????flags = fcntl(fd,F_GETFL,0);
??????flags &= ~O_NONBLOCK;
????? fcntl(fd,F_SETFL,flags);
獲取和設(shè)置文件flags舉例::
char buf[500000];
int main(int argc,char *argv[])
{
int ntowrite, nwrite;
const char *ptr ;
int flags;
ntowrite = read(STDIN_FILENO,buf,sizeof(buf));
if(ntowrite < 0)?
{?
????????perror("read STDIN_FILENO fail:");
????????exit(1);
}?
fprintf(stderr,"read %d bytes\n",ntowrite);
if (( flags = fcnt l(STDOUT_FILENO ,F_GETFL,0 )) == -1)
{?
????????perror("fcntl F_GETFL fail:");
????????exit(1);
}?
?flags |= O_NONBLOCK;
?if ( fcntl( STDOUT_FILENO, F_SETFL, flags ) == -1)
{?
????????perror("fcntl F_SETFL fail:");
????????exit(1);
}?
ptr = buf;
while(ntowrite > 0)
{?
????????nwrite = write(STDOUT_FILENO,ptr,ntowrite);
????????if ( nwrite == -1)?
????????{
? ??????????????perror("write file fail:");
????????}?
????if ( nwrite > 0)
????{?
????????ptr += nwrite;
????????ntowrite -= nwrite;
????}?
}?
?flags &= ~O_NONBLOCK;
?if ( fcntl( STDOUT_FILENO, F_SETFL, flags) == -1)
{?
????????????????perror("fcntl F_SETFL fail2:");
?}?
return 0;
}