定义一个管道类Pipe,包含两个私有成员变量:一个数组data和一个整数capacity,用来存储数据和表示容量。
实现Pipe类的构造函数,初始化成员变量data和capacity,并且在构造函数中使用pipe函数创建一个管道,并判断是否成功创建。
#include
#include
#include
#include
#define BUFFER_SIZE 1024
class Pipe {
private:
char data[BUFFER_SIZE];
int capacity;
public:
int fd[2];
Pipe() {
this->capacity = BUFFER_SIZE;
if (pipe(fd) == -1) {
perror("Failed to create pipe:");
exit(EXIT_FAILURE);
}
}
~Pipe() {
close(fd[0]);
close(fd[1]);
}
};
class Pipe {
...
public:
...
int read_data() {
int readable = 0;
ioctl(fd[0], FIONREAD, &readable);
if (readable > 0) {
int read_size = read(fd[0], data, BUFFER_SIZE);
if (read_size > 0) {
std::cout << "Read data:" << data << std::endl;
return read_size;
}
}
return -1;
}
int write_data(const char* buffer) {
int write_size = write(fd[1], buffer, BUFFER_SIZE);
std::cout << "Write data:" << buffer << std::endl;
return write_size;
}
};
struct User {
char name[20];
int age;
};
...
class Pipe {
...
public:
...
int read_struct(void* buf, size_t size) {
int readable = 0;
ioctl(fd[0], FIONREAD, &readable);
if (read