簡介
標准 I/O 庫(stdio)及其頭文件 stdio.h 為底層 I/O 系統調用提供了一個通用的接口。這個庫現在已經成為 ANSI 標准 C 的一部分。
標准 I/O 庫提供了許多復雜的函數用於格式化輸出和掃描輸入。在很多方面,你使用的標准 I/O 庫的方式和使用底層文件描述符一樣,
需要先打開一個文件以建立一個訪問路徑,這個操作的返回值將作為其他 I/O 庫函數的參數。
在標准 I/O 庫中,與底層文件描述符對應的是流(stream,需要注意的是這個流與 C++ 中的輸入輸出流不一樣),
它被實現為指向結構 FILE 的指針(文件指針)。
在啟動程序時,有 3 個文件流是自動打開的,它們是 stdin、stdout 和 stderr,
在 stdio.h 中定義,分別代表着標准輸入、標准輸出和標准錯誤輸出,與底層文件描述符 0、1、2 相對應。
可用的文件流數量與文件描述符一樣,都是有限制的,實際的限制由頭文件 stdio.h 中定義的 FOPEN_MAX 來定義,它的值至少為 8,在 Linux 系統中,通常是 16。
#在子進程中關閉標准輸出,觀察對父進程的影響
#include<stdio.h> #include<unistd.h> #include<sys/wait.h> #include<sys/types.h> int main(){ int rc=fork(); if(rc==0){ printf("child print a word\n"); fclose(stdout); printf("not print \n"); }else{ wait(NULL); printf("father"); } return 0;} [root@localhost codec5]# ./t7 child print a word father
顯然在再子進程中關閉對父進程並沒有影響。
下面我們用waitpid使子進程等待父進程,然后再父進程里面調用了fclose(stdout)將標准輸出關掉了,父進程后面的沒有輸出,子進程正常
#include<stdio.h> #include<unistd.h> #include<sys/wait.h> #include<sys/types.h> int main(){ int w=(int)getpid(); int rc=fork(); if(rc==0){ waitpid(w,NULL,0); printf("child print a word\n"); printf("not print \n"); }else{ printf("output\n"); fclose(stdout); printf("father\n"); } return 0;} [root@localhost codec5]# ./t7 output [root@localhost codec5]# child print a word not print
如果在fork前調用fclose(stdout)很顯然父子進程均不會有任何輸出
如下代碼
#include<stdio.h> #include<unistd.h> #include<sys/wait.h> #include<sys/types.h> int main(){ fclose(stdout); int rc=fork(); if(rc==0){ printf("child print a word\n"); printf("not print \n"); }else{ printf("output\n"); printf("father\n"); } return 0;} 無輸出