查看積分策略說明發表回覆
Discuz! 代碼
提示插入
直接插入
說明訊息

插入粗體文本 插入斜體文本 插入下劃線 置中對齊 插入超級連結 插入信件位址 插入圖像 插入 flash 插入代碼 插入引言 插入列表
刪除線 直線分隔線 虛線分隔線
    
添加文字底框
內容 [字數檢查]:

表情符號

更多 Smilies
字型大小 |||
溫馨提示:本區開放遊客瀏覽。


文章關鍵字 : [功能說明]
(關鍵字可加強搜索準確性, 如關鍵字多於一組, 請以 , 作分隔, e.g. : 阿笨,shiuh,第一笨)

 關閉 URL 識別 | html 禁用
 關閉 表情符號 | 表情符號 可用
 關閉 Discuz! 代碼 | Discuz! 代碼 可用
使用個人簽名
接收新回覆信件通知
推薦放檔網絡空間

檔案(Torent, zip等)
  1. freedl
  2. multiupload
  3. btghost
  4. 便當狗
  5. mediafire
  6. pillowangel
圖片(JPG, GIF等)
  1. hotimg
  2. tinypic
  3. mousems2
  4. imageshack
  5. imm.io
>>>歡迎推薦好用空間


最新10篇文章回顧
yyyy1234

 發表於 2014-2-18 12:23 PM

對一般熟悉 Linux TCP/IP socket programming 的programmer 來說,要做 file transfer 的工作最常使用的方法就是用 open()  將要傳送的 file 打開, , 然後用read()藉由 open() 所產生的file descriptor將讀到的 內容copy到 buffer 然後用write()藉由 socket() 所產生的file descriptor 將 buffer 的內容 透過 TCP/IP protocol傳輸到目的. 所以程式都將有類似的 routine:

   Do_read(file_fd, buffer, len); // 讀file 內容的routine
   Do_wite(socket_fd, buffer, len); // socket 傳輸 routine

由於 read() , write() 皆是在 user space 的 system call, 程式執行時 read() ,write() 均須將相同 buffer 的內容copy 進出 kernel space , 這不是一個非常有效率的方法, 尤其是當傳輸的檔案size相當大時 ( > 1 Gbyte) , 程式執行時間也會較久 . Linux 提供了另一個選擇: sendfile() , 它號稱是所謂的 zero-copy, 就是sednfile() system call 本身無需做buffer copy 進出 kernel space 的動作, 既能將 讀到的buffer 內容藉由 socket 傳輸到目的地, 可減少程式執行時間 . 以下是範例如何使用 sendfile() 達到和上面routine 一樣的功能.



ssize_t do_sendfile(int sock_fd, int file_fd, off_t offset, size_t count) {
    ssize_t bytes_sent;
    size_t total_bytes_sent = 0;
    while (total_bytes_sent < count) {
        if ((bytes_sent = sendfile(sock_fd, file_fd, &offset,
                count - total_bytes_sent)) <= 0) {
            if (errno == EINTR || errno == EAGAIN) {
                // Interrupted system call/try again
                // Just skip to the top of the loop and try again
                continue;
            }
            perror("sendfile");
            return -1;
        }
        total_bytes_sent += bytes_sent;
    }
    return total_bytes_sent;
}

以上的範例我是由此篇文章 (http://blog.superpat.com/2010/06 ... ndfile-and-splice/) 中 copy 出來供各位做參考.





所在時區為 GMT+8, 現在時間是 2024-3-29 11:57 PM
清除 Cookies - 連絡我們 - TWed2k © 2001-2046 - 純文字版 - 說明
Discuz! 0.1 | Processed in 0.016153 second(s), 6 queries , Qzip disabled