<unix進階編程>筆記 chapter1

來源:互聯網
上載者:User

標籤:class   blog   code   http   ext   檔案   

os嚴格上是軟體,為電腦提供資源和app運行環境. 特稱為核心.

核心的介面被成為system call;然後庫函數對system call進行了封裝;shell是特殊app,為運行其他程式提供了一個介面.

shell是個命令列解譯器,讀取輸入,執行命令.

unix檔案系統是由directory和file組成.目錄起點成為root,名字是/.

檔案屬性指類型\大小\所有者\許可權以及修改時間.stat和fstat返迴文件屬性的結構.

比如下面操作:




2.檔案名稱

只有/和null不能出現在檔案名稱裡.因為/用來分割構成路徑名,null用來終止一個路徑名.

建立新目錄的適合會自動建立兩個檔案名稱.和..

點指目前的目錄,..指上一級目錄.


3.路徑名

一個或者多個/構成路徑名.

以/開頭指相對路徑,否則是絕對路徑. 其實經常用的是相對路徑.


實戰:

1.列出目錄下的所有檔案.就是實現ls功能.

#include <dirent.h>#include "stdio.h"#include "stdlib.h"int main(int argc, char** argv){    if (argc != 2){        printf("usage: ls dir_name\n");        return 1;    }    DIR* dp = opendir(argv[1]);    if (NULL == dp){        printf("can't open %s\n", argv[1]);        return 1;    }    printf("load dir success\n");    struct dirent* dirp = NULL;    while ((dirp = readdir(dp)) != NULL)        printf("%s ", dirp->d_name);    printf("\n");    closedir(dp);    return 0;}

從結果看出來 . 和.. 的確是有效目錄.列印結果是無序的.而ls結果是有序的.

exit(0)標示程式正常退出.1-255表示錯誤碼.


1.5 輸入和輸出


fd是個非負整數.是核心用來標示特定進程正在訪問的檔案.

每當shell被開啟,都有三個預設fd被開啟:stdin stdout stderror

另外shell可以方便地重新導向.

3)不用緩衝的IO

open read close write lseek 提供了不用緩衝的IO

代碼:

#include "stdio.h"#include "unistd.h"int main(){    int n = 0;    const int maxLen = 4096;    char buff[maxLen];    while ((n == read(STDIN_FILENO, buff, maxLen)) > 0){        if (write(STDOUT_FILENO, buff, n) != n){            printf("error\n");            exit(1);        }    }        exit(0);}

標示這代碼不是很理解,明天來看.

就學到這裡.



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.