write()這個system call函式的用法很簡單.以下是write()的宣告


write(int, const void*, unsigned int);


write()這個函式的用處就是把第二個和第三個參數所指向的資料寫進第一個參數所代表的檔案或設備裡.在C裡,你可以用open()這個函式來打開一個檔案或設備.open()打開你要的檔案或設備之後會回傳一個整數代表其檔案或設備.當你要存資料進那個檔案或設備時你就可以用write()來存.在呼叫write()時傳入那個整數為第一個參數.然後把你要寫的資料作為第二和三個參數即可.要如何用第二和第三參數代表你要寫的資料呢?第二參數是個指標,指向你要寫的資料的起頭.第三參數是個整數,代表你要寫多少個bytes.例:


#include <fcntl.h>
#include <string.h>
int main()
{
    int f;
    char *data = "hello world"; /* data是個字串指標.指向”hello world” */
   
    f = open("hello", O_WRONLY|O_CREAT, 0700); /* 開個名叫hello的檔 */
    write(f, data, strlen(data)); /* 用write()把hello world寫進hello這個檔裡 */
    close(f); /* 關檔 */
    return(0);
}


在這程式裡.在用write()時我傳入f為第一個參數.因為f代表hello這個檔.而我要存東西進這個檔.所以傳入f為第一個參數.我傳data為第二個參數是因為我要存”hello world”進hello這個檔,data這個字串指標指向”hello world”這個字串.所以傳入data為第二個參數.我傳strlen(data) 為第三個參數是因為strlen(data)會告訴我data指向的字串總共有幾個字元.所以這個write()函式的意思是.從data指向的資料裡取出strlen(data)個bytes然後寫進f裡.


Ok,現在知道write()的用法.我再來講如何用write()來替代printf().在C裡.0代表輸入(stdin),1代表輸出(stdout),2代表錯誤(stderr).也就是說你若在呼叫write()時傳入1為第一個參數的話那你存入的資料將會被顯示出來.以你的例子來說


write(1, "PID: 970, Parent PID: 969n", 26);


你傳入1為第一個參數.所以write()會把"PID: 970, Parent PID: 969n"裡的前26個字元顯示出來.也就是說這個write()會顯示


PID: 970, Parent PID: 969


所以當你要把printf()改成write()時你只要以1為第一個參數然後把printf()會顯示出來的資料用第二和第三個參數傳入write().這樣就行了.例:


printf(“hello”); == write(1, “hello”, strlen(“hello”));


printf(“hello”);會顯示”hello”這個字串.所以write()的第二個參數是”hello”,第三個參數是strlen(“hello”)因strlen(“hello”)等於5.要顯示”hello”裡前5個字元.

arrow
arrow
    全站熱搜

    deskwoodss 發表在 痞客邦 留言(2) 人氣()