Linux系统编程P8

阅读: 评论:0

Linux系统编程P8

Linux系统编程P8

文件与I/O(四)

文件描述符0:标准输入,一般为阻塞状态
文件描述符1:标准输出
代码示例:

#include<stdio.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<errno.h>
#include<string.h>
#include <unistd.h>
#define ERROR_EXIT(m) (perror(m),exit(EXIT_FAILURE))
#define MAJOR(a) (int)((unsigned short)a>>8)
#define MINOR(a) (int)((unsigned short)a & 0xFF)
int filetype(struct stat * buf);
int main(int argc, char* argv[])
{char buf[1024]={0};int flag;int ret;//获取状态信息,0文件描述符表示输入一般为阻塞状态flag=fcntl(0,F_GETFL,0);if(flag==-1)ERROR_EXIT("get state error");//设置文件描述符状态信息,为非阻塞状态ret=fcntl(0,F_SETFL,O_NONBLOCK);if(ret==-1)ERROR_EXIT("set state error");ret=read(0,buf,1024);if(ret==-1)ERROR_EXIT("read error");printf("buf=%sn",buf);
}


错误原因:
man 2 read:

#include<stdio.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<errno.h>
#include<string.h>
#include <unistd.h>
#define ERROR_EXIT(m) (perror(m),exit(EXIT_FAILURE))
#define MAJOR(a) (int)((unsigned short)a>>8)
#define MINOR(a) (int)((unsigned short)a & 0xFF)
int filetype(struct stat * buf);
void set_flags(int fd,int flags);
void clr_flags(int fd,int flags);
int main(int argc, char* argv[])
{char buf[1024]={0};int flag;int ret;
"04fcntl.c" 55L, 1452C
void set_flags(int fd,int flags){int val;val=fcntl(fd,F_GETFL,0);if(val==-1)ERROR_EXIT("get error");val |= flags;if(fcntl(fd,F_SETFL,val)<0)ERROR_EXIT("set error");}
void clr_flags(int fd,int flags){int val;val=fcntl(fd,F_GETFL,0);if(val==-1)ERROR_EXIT("get error");val &= ~flags;if(fcntl(fd,F_SETFL,val)<0)ERROR_EXIT("set error");}

锁的用法代码示例(struct flock):

#include<stdio.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<errno.h>
#include<string.h>
#include <unistd.h>
#define ERROR_EXIT(m) (perror(m),exit(EXIT_FAILURE))
#define MAJOR(a) (int)((unsigned short)a>>8)
#define MINOR(a) (int)((unsigned short)a & 0xFF)
int filetype(struct stat * buf);
int main(int argc, char* argv[])
{//设置锁int fd=open("test5.c",O_CREAT | O_RDWR | O_TRUNC,0644);if(fd==-1)ERROR_EXIT("open error");struct flock lock;memset(&lock,0,sizeof(lock));lock.l_type=F_WRLCK;lock.l_whence=SEEK_SET;lock.l_start=0;lock.l_len=0;//对文件加锁,如果成功,另一个进程无法加锁if(fcntl(fd,F_SETLK,&lock)==0){printf("lock successn");printf("press any key to unlockn");getchar();lock.l_type=F_UNLCK;if(fcntl(fd,F_SETLK,&lock)==0){printf("unlock successn");}else{ERROR_EXIT("unlock fail");}}else{ERROR_EXIT("lock fail");}return 0;
}

fcntl

fcntl常用操作

文件锁结构体

本文发布于:2024-01-28 20:16:43,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170644420810006.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:系统   Linux
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23