Linux基礎(一)系統api與庫函數的關係

1. 系統api與庫函數的關係

 

man 2 openapi

 

1.1 open

1.2 read/write

實現cat功能網絡

#include <stdio.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h>


int main(int argc, char *argv[]) { if (argc != 2) { printf("./a.out filename\n"); return -1; } int fd = open(argv[1], O_RDONLY); //讀,輸出到屏幕
    char buff[200]; int ret = 0; while (ret = read(fd, buff, sizeof(buff))) { write(STDOUT_FILENO, buff, ret); } close(fd); return 0; }

1.3 lseek

#include <stdio.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h>


int main(int argc, char *argv[]) { if (argc != 2) { printf("./a.out filename\n"); return -1; } int fd = open(argv[1], O_RDWR|O_CREAT, 0666); write(fd, "helloword", 11); //文件讀寫的位置此時到末尾 //須要移動讀寫的位置
    lseek(fd, 0, SEEK_SET); char buf[256] = {0}; int ret = read(fd, buf, sizeof(buf)); if (ret) { write(STDOUT_FILENO, buf, ret); } close(fd); return 0; }

 計算大小函數

int fd = open(argv[1], O_WRONLY); int ret = lseek(fd, 0, SEEK_END); printf("file size is %d\n", ret); close(fd);

拓展文件spa

//1. open
    int fd = open(argv[1], O_WRONLY|O_CREAT, 0666); int ret = lseek(fd, 1024, SEEK_END); printf("file size is %d\n", ret); //須要至少寫一次,不然不能保存
    write(fd, "a", 1); close(fd);

1.4 阻塞

  • read函數在讀設備或者的讀管道,或者讀網絡的時候。
  • 輸入輸出設備對應 /dev/tty
int fd = open("/dev/tty", O_RDWR|O_CREAT|O_NONBLOCK);

1.5 fcntl函數--設置非阻塞

#include <unistd.h> #include <fcntl.h>

int fcntl(int fd, int cmd, ... /* arg */ );
int flags = fcntl(fd, F_GETFL); flags |= O_NONBLOCK;
相關文章
相關標籤/搜索