1.open/close函数
(1)open函数用于打开文件,打开或者创建文件时候可以修改设定各种参数
(2)close函数用于关闭文件
2.read、write、lseek。
(1)read函数用于独处制定文件描述符中的数据
(2)write 函数是用于打开文件并写入数据,写操作从当前文件的位移量位置处开始
(3)lseek函数用于在指定文件描述符中将文件指针定位到相应的位置
3.fcntl函数
fcntl主要用于给Linux给文件上锁,防止同时操作同一文件。
lock结构体:
struct flock{
short l_type;
off_t l-start;
short l_whence;
off_t l_len;
pid_t l_pid;
}
lock结构体中每天一个变量的取值
4.select
select函数主要解决文件共享问题
select 函数中用到了struct timeval 类型函数指针。
结构如下:
struct timeval{
long tv_sec;
long tv_unsec;
}
#include<fcntl.h>
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<time.h>
int main(void)
{
int fds[2];
char buf[7];
int i,rc,maxfd;
fd_set inset1,inset2;
struct timeval tv;
if((fds[0]=open("hello1",O_RDWR|O_CREAT,0666))<0)
perror("open");
if((fds[1]=open("hello2",O_RDWR|O_CREAT,0666))<0)
perror("open");
if((rc=write(fds[1],"hello!\n",7)))
printf("rc=%d\n",rc);
lseek(fds[0],0,SEEK_SET);
maxfd=fds[0]>fds[1]?fds[0]:fds[1];
FD_ZERO(&inset1);
FD_SET(fds[0],&inset1);
FD_ZERO(&inset2);
FD_SET(fds[1],&inset2);
tv.tv_sec=2;
tv.tv_usec=0;
while((FD_ISSET(fds[0],&inset1))||(FD_ISSET(fds[1],&inset2)))
{
if(select(maxfd+1,&inset1,&inset2,NULL,&tv)<0)
perror("select");
else
{
if(FD_ISSET(fds[0],&inset1))
{
rc=read(fds[0],buf,7);
if(rc>0)
{
buf[rc]='\0';
printf("read;%s\n",buf);
}else
perror("read");
}
if(FD_ISSET(fds[1],&inset2))
{
rc=write(fds[1],buf,7);
if(rc>0)
{
buf[rc]='\0';
printf("rc=%d,wrire:%s\n",rc,buf);
}else
perror("write");
sleep(10);
}
}
}
exit(0);
}