linux-sys_文件IO

来源:互联网 发布:程序员工资 知乎 编辑:程序博客网 时间:2024/06/06 12:33

1.C标准函数与系统函数的区别

C语言提供的IO API有缓冲区(buffer) 大小:8192B

linux提供的IO没有缓冲区。


2.PCB概念

文件描述符: 一个进程默认打开3个文件描述符

STDIN_FILENO 0

STDOUT_FILENO 1

STDERR_FILENO 2


vim中, man 2 open 查看open函数原型


tags:

O_CREAT   //创建文件

O_EXCL  //创建文件时,如果文件存在则出错返回

O_TRNUC    //把文件截断成0

O_RDONLY   //只读(互斥)

O_WRONLY   //只写(互斥)

O_RDWR     //读写(互斥)

O_APPEND   //追加,移动文件读写指令位置到文件末尾

O_NONBLOCK    //非阻塞标志

O_SYNC    //使每次write都等到物理I/O操作完成,包括文件属性的更新


#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>int open(const char *pathname,int flags);int open(const char *pathname,int flags,mode_t mode);返回值:返回一个文件描述符表中未使用的最小文件描述符。             #include <unistd.h>int close(int fd);返回值:成功返回0,出错返回-1并设置errno 

3.最大打开文件个数

cat /proc/sys/fs/file-max     查看当前系统允许打开最大文件个数  

ulimit -a   查看当前系统设置最大打开文件个数 1024

ulimit -n 4096 修改默认设置最大文件个数为4096


4.read/write

#include <unistd.h>

ssize_t read(int fd,void *buf,size_t count);

返回值:成功返回读取字节数,出错返回-1并设置errno,如果在调read之前已达文件末尾,则这次返回0


#include <unistd.h>

ssize_t write(int fd,const void *buf,size_t count);

返回值:成功返回写入字节数,出错返回-1并设置errno


5. 阻塞非阻塞概念

非阻塞程序:

#include <unistd.h>
#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>

#define MSG_TRY "try again\n"

int main(void)
{
char buf[10];
int fd, n;
fd = open("/dev/tty", O_RDONLY|O_NONBLOCK);
if(fd<0)
{
perror("open /dev/tty");
exit(1);
}
tryagain:
n = read(fd, buf, 10);
if (n<0)
{
if(errno == EAGAIN)
{
sleep(1);
write(STDOUT_FILENO, MSG_TRY, strlen(MSG_TRY));
goto tryagain;
}
perror("read /dev/tty");
exit(1);
}
write(STDOUT_FILENO, buf, n);
close(fd);
return 0;
}




6.perror   errno


7.lseek

#include <sys/types.h>

#include <unistd.h>

off_t lseek(int fd, off_t offset, int whence);


#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include <unistd.h>#include <stdlib.h> int main(void){    int fd = open("abc",O_RDWR);    if (fd<0)    {         perror("open abc");         exit(-1);    }     lseek(fd,0x1000,SEEK_SET);    write(fd,"a",1);   //扩展一个文件,一定要有一次写操作    close(fd);    fd = open("hello", 0_RDWR);    if (fd < 0)    {        perror("open hello");        exit(-1);    }    printf("hello size = %d\n", lseek(fd, 0, SEEK_END));    close(fd);    return 0; }8.fcntl  (可以改变 File Status Flag)#include <unistd.h>#include <fcntl.h>int fcntl(int fd, int cmd);int fcntl(int fd, int cmd, long arg);int fcntl(int fd, int cmd, struct flock *lock);9.ioctl#include<sys/ioctl.h>int ioctl(int d, int request, ...)