样例代码如下:
#include
#include
#include
#include
#include
#include
#include
int main() {
// 定义命名管道的路径
const char* pipe_path = "/tmp/my_pipe";
// 创建命名管道
mkfifo(pipe_path, 0666);
// 打开命名管道进行读写操作
int pipe_fd = open(pipe_path, O_RDWR | O_NONBLOCK);
// 非阻塞读取命名管道中的数据
char buffer[1024];
ssize_t bytes_read;
while ((bytes_read = read(pipe_fd, buffer, sizeof(buffer))) > 0) {
std::cout.write(buffer, bytes_read);
std::cout << "haha" << std::endl;
}
printf("bytes_read = %ld, errno = %d\n", bytes_read, errno);
if (bytes_read == -1 && errno == EAGAIN) {
perror("Error reading from pipe");
// return 1;
}
// 非阻塞写入数据到命名管道
const char* data_to_write = "Hello, World!";
ssize_t bytes_written = write(pipe_fd, data_to_write, strlen(data_to_write));
if (bytes_written == -1 && errno == EAGAIN) {
perror("Error writing to pipe");
return 1;
}
bytes_written = write(pipe_fd, data_to_write, strlen(data_to_write));
if (bytes_written == -1 && errno == EAGAIN) {
perror("Error writing to pipe");
return 1;
}
while ((bytes_read = read(pipe_fd, buffer, sizeof(buffer))) > 0) {
std::cout.write(buffer, bytes_read);
std::cout << "haha" << std::endl;
}
// 关闭命名管道
close(pipe_fd);
unlink(pipe_path);
return 0;
}
经过测试,命名管道的空间还挺大的,使用非阻塞写入可以连续两次写入。
面对连续多次被写入的命名管道,只要不超出一次读管道的字符限制,一次读管道就能读出所有数据
如果读的时候命名管道里没有东西,read 系统调用会返回 -1,同时 errno 会被设置成 EAGAIN,告知一段时间后重试