Linux-C-Day1

相關函數
  • open
  • close
  • read
  • write
  • perror
  • sleep // 秒
  • goto
相關宏
  • errno
  • STDIN_FILENO
  • STDOUT_FILENO
#include <fcntl.h> // open(), fcntl : file control
#include <unistd.h> // close()  , unistd: unix standard header
#include <stdio.h>
#include <stdlib.h> // 標準庫函數
#include <errno.h> // 記錄每一次函數調用的錯誤碼, 配合使用 errno

int main() {
    // 打開文件,返回FD
    if (open("aaa", O_RDONLY) < 0){
        perror("open file 'aaa'");
        exit(2);
    }

    int fd;
    if ((fd = open("some_file.txt", O_WRONLY | O_CREAT, 0644)) < 0) {
        printf("file open failed\n");
        exit(1);
    }

    printf("FD: %d\n", fd);

    // 關閉文件
    if (close(fd)) {
        printf("file close failed : %d\n", errno);
        exit(1);
    }

    printf("中文File open and close successfully\n");
    
    // 從標準輸入文件,讀入文件,輸出到標準輸出
    char buf[10];
    ssize_t n;
    // 這裏會阻塞當前 進程
    n = read(STDIN_FILENO, buf, 10);
    if (n < 0) {
        perror("read STDIN_FILENO");
        exit(1);
    }

    write(STDOUT_FILENO, buf, n);

    return 0;
}

非阻塞read

#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <stdio.h>

#define MSG_TRY "try again \n"

int main(void) {
    char buf[10];
    int fd;
    ssize_t n = 0;
    fd = open("/dev/tty", O_RDONLY | O_NONBLOCK);

    if (fd < 0) {
        perror("open /dev/tty");
        exit(1);
    }

try_again:

    n = read(fd, buf, n);
    if (n < 0) {
        if (errno == EAGAIN) {
            // sleep 1 sec
            sleep(1);
            write(STDOUT_FILENO, MSG_TRY, strlen(MSG_TRY));
            goto try_again;
        }
        perror("read /dev/tty");
        exit(1);
    }

    write(STDOUT_FILENO, buf, n);
    close(fd);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章