有没有办法控制通过mkfifo
创建的命名管道的缓冲区大小?
我正在使用macOS 10.13.2,缓冲区大小似乎固定为8192字节。我能用这段代码获得这个数字:
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <thread>
#define BUFFER_SIZE 1024*1024
#define FIFO_PATH "/Users/joao/Desktop/fifo"
void readFifo() {
auto fd = open(FIFO_PATH, O_RDONLY);
if (fd < 0) {
std::cerr << "Failed to open fifo for reading" << std::endl;
return;
}
std::cout << "Ready to read!" << std::endl;
char buffer[BUFFER_SIZE];
auto total_bytes_read = 0;
while (total_bytes_read < BUFFER_SIZE) {
auto bytes_read = read(fd, buffer, BUFFER_SIZE);
std::cout << "Read " << bytes_read << " bytes" << std::endl;
total_bytes_read += bytes_read;
}
close(fd);
}
int main(int argc, const char * argv[]) {
unlink(FIFO_PATH);
if (mkfifo(FIFO_PATH, 0666) != 0) {
std::cerr << "Failed to create fifo" << std::endl;
return 1;
}
std::thread reader(readFifo);
auto fd = open(FIFO_PATH, O_WRONLY);
if (fd < 0) {
std::cerr << "Failed to open fifo for writing" << std::endl;
return 1;
}
char buffer[BUFFER_SIZE];
for (int i = 0; i < BUFFER_SIZE; i++) {
buffer[i] = 'a';
}
auto bytes_written = write(fd, buffer, BUFFER_SIZE);
reader.join();
std::cout << "Wrote " << bytes_written << " bytes" << std::endl;
unlink(FIFO_PATH);
return 0;
}