這個問題在這里已經有了答案: 在哪里可以找到所有 C 標準庫的源代碼? (4 個回答) 7 小時前關閉。
在瀏覽 C ( ) 的標準庫函式時glibc
,我發現printf()
實際上呼叫了puts()
函式 ( _IO_puts
)。但我無法找出 puts 函式實際上是如何寫入stdout
?
它是否使用write()
定義的系統呼叫unistd.h
或其他東西?我發現一件事puts()
實際上是_IO_xputn
通過_IO_putn
.
請幫忙。謝謝你。
uj5u.com熱心網友回復:
對于 Linux 所在的基于 Unix 的系統,stdio 庫中的大多數函式都是在標準 I/O 系統呼叫之上一層的包裝器。您會看到,作業系統提供了一組稱為系統呼叫的 API。應用程式不能直接訪問硬體資源,因此它們通常在需要執行任何型別的特權操作(例如寫入螢屏或從鍵盤讀取)時呼叫這些“系統呼叫”。
在 Unix 中,一切都被抽象為一個檔案,所以每當您需要將字符寫入螢屏時,您所需要做的就是打開一些代表“螢屏”的檔案并將這些字符寫入那里。內核將負責其余的作業。很簡單,這就是您在 C 中執行此操作的方式:
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#define BUFF_SIZE 2
int main()
{
int terminal;
char buffer[BUFF_SIZE] = "C\n"; // This will store the character to print new line
terminal = open("/dev/tty", O_WRONLY); // systemcall to open terminal
if (terminal < 0)
exit(1); // some error happened
dup2(terminal, STDOUT_FILENO); // use our newly opened terminal as default Standard output
if (write(terminal, buffer, BUFF_SIZE) != BUFF_SIZE) // systemcall to write to terminal
exit(1); // We couldn't write anything
}
這只是向您展示 stdio 中的所有內容都位于基本 I/O 系統呼叫之上。這些系統呼叫是讀、寫、打開等。如果你想了解更多關于系統呼叫和一些作業系統內部的知識,請閱讀 Andrea Arpaci-Dusseau 的《三個簡單的部分》一書
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/450175.html