1 System Calls, File Management and Device I/O
1.用户使用C standard library,调用malloc() calloc()
,真实的空间申请是系统调用sbrk()
2.
2 Hello World (again)
1.假设没有C standard library(fopen,fwrite,fread),我们就需要低等级的函数,既系统调用,直接写入device
#include <unistd.h>
int main(int argc, char * argv[]){
char hello[] = "Hello World\n";
char *p;
for(p = hello ; *p ; p++){
write(1, p, 1);
}
}
2.1 Basics of write() to terminal
1.read() and write()操作文件描述符(fd),而不是文件流(file stream);
2.read from or write to buffers not strings
// .-- Write to standard out, file descriptor 1
// v
write(1, p, 1);
// ^ ^
// | '--- Number of bytes to write, just the char p points to
// |
// '-------- char *, points to the byte we want to write
3 read() and write() in Detail
3.1 write()'ing a Buffer of Bytes
1.A buffer is the general term for an array of bytes.
ssize_t write(int fd, const void *buf, size_t count);
// ^ ^ ^
//file descriptor---' buffer--' '-- num. bytes to write
3.2 read()'ing a Buffer of Bytes
ssize_t read(int fd, void *buf, size_t count);
// ^ ^ ^
//file descriptor---' buffer--' '-- num. bytes to write
4 Opening Files
4.1 File descriptors
4.2 open()'ing a File Descriptor
int open(const char *path, int oflag, ... /*mode_t mode*/ );
int fd = open("path/to/file", O_RDONLY);
int fd = open("test.txt", O_WRONLY | O_TRUNC | O_CREAT, 0664);
1.open
来自fcntl.h
,系统级;fopen()
来自stdlib.h
,用户级
2.oflag
flag | 描述 |
---|---|
O_RDONLY | open for reading only |
O_WRONLY | open for writing only |
O_RDWR | open for reading and writing |
O_APPEND | append on each write |
O_CREAT | create file if it does not exist |
O_TRUNC | truncate size to 0 |
3.mode
mode | 描述 |
---|---|
S_IRUSR 00400 | owner has read permission |
S_IWUSR 00200 | owner has write permission |
S_IXUSR 00100 | owner has execute permission |
S_IRGRP 00040 | group has read permission |
S_IWGRP 00020 | group has write permission |
S_IXGRP 00010 | group has execute permission |
S_IROTH 00004 | others have read permission |
S_IWOTH 00002 | others have write permission |
S_IXOTH 00001 | others have execute permission |
4.3 User Masks for File Creation
1.umask用来处理用户权限