分散/聚集I/O是一種可以在單詞系統調用對多個緩沖區輸入輸出的方法,可以把多個緩沖區的數據寫到單個數據流中,也可以把單個數據流讀到多個緩沖區中。其命名的原因在于數據會被分散到指定緩沖區向量,或者從指定緩沖區向量中聚集數據。這種輸入輸出方法也稱為向量I/O(vector I/O)。標準讀寫系統調用可以稱為線性I/O(linear I/O)。
Linux中定義了一組實現滿足上述所有特性的分散/聚集I/O的系統調用。它們分別為:
// readv()函數從文件描述符fd中讀取count個段到參數iov所指定的緩沖區中。// 返回讀取的字節個數#include <sys/uio.h>ssize_t readv (int id, const struct iovec *iov, int count);// writev()函數將iov指定的緩沖區中讀取count個段的數據,并寫入fd中。// 返回寫入的字節個數#include <sys/uio.h>ssize_t writev (int id, const struct iovec *iov, int count);其中結構體iovec的定義如下:
struct iovec { void *iov_base; size_t iov_len;};每個段描述了內存中所要讀寫的緩沖區的地址和長度。readv()函數在處理下一個緩沖區之前,會填滿當前緩沖區的iov_len個字節。writev()函數在處理下一個緩沖區之前,會把當前緩沖區的iov_len個字節數據輸出。這兩個函數都會順序處理向量中的段,從0到count-1。
注意:
由于返回值類型是ssize_t,如果所有count個iov_len的和超過SSIZE_MAX,則不會處理任何數據,返回-1,并把errno值設為EINVAL。POSIX指出count的值必須大于0,且小于IOV_MAX(在文件#include <iostream>#include <unistd.h>#include <fcntl.h>#include <sys/uio.h>#include <sys/types.h>#include <sys/stat.h>#include <limits.h>#include <cstdio>using namespace std;int main(int argc, char *argv[]){ struct iovec iov[3]; int count = 3; string buffer[3] = { "The term buccaneer comes from the Word boucan./n", "A boucan is a wooden frame used for cooking meat./n", "Buccaneer is the West Indives name for a pirate./n" }; int fd; fd = open("buccaneer.txt", O_WRONLY | O_CREAT); if (-1 == fd) { perror("open failed"); return 1; } for (int i=0; i<3; i++) { iov[i].iov_len = buffer[i].size() + 1; iov[i].iov_base = const_cast<char *> (buffer[i].c_str()); cout << iov[i].iov_len << endl; } ssize_t nr; nr = writev(fd, iov, 3); if (-1 == nr) { perror("writev error"); return 1; } cout << "wrote " << nr << " bytes" << endl; if (close(fd)) { perror("close"); return 1; } return 0;}#include <iostream>#include <cstdio>#include <sys/types.h>#include <sys/uio.h>#include <sys/stat.h>#include <fcntl.h>#include <unistd.h>using namespace std;int main(int argc, char *argv[]){ struct iovec iov[3]; ssize_t nr; int fd; fd = open("buccaneer.txt", O_RDONLY); if (-1 == fd) { perror("open error"); return 1; } iov[0].iov_base = new char[48]; iov[0].iov_len = 48; iov[1].iov_base = new char[51]; iov[1].iov_len = 51; iov[2].iov_base = new char[50]; iov[2].iov_len = 50; // read into the structure nr = readv(fd, iov, 3); if (-1 == nr) { perror("readv error"); return 1; } for (int i=0; i<3; i++) cout << i << ": " << static_cast<char *> (iov[i].iov_base) << endl; if (close(fd)) { perror("close error"); return 1; } return 0;}新聞熱點
疑難解答