У меня есть труба, обеспечивающая связь между двумя процессами в разветвленной программе. Он был создан с помощью вызова pipe() - http://linux.die.net/man/2/pipe . Все идет правильно, пока я не хочу выполнять некоторые операции с файлами.Операции с вилками, трубами и файлами
Этот код работает:
pipe.writeBuffer(message.c_str(), message.length());
ofstream file;
file.open(name.c_str(), ios::app);
file << "stringData"; // put some data to file (many times)
Но это не:
ofstream file;
file.open(name.c_str(), ios::app);
pipe.writeBuffer(message.c_str(), message.length());
file << "stringData"; // put some data to file (many times)
Во втором примере нет никакого эффекта "файл < < someStream" - я получаю пустой файл. Что не так с этим? Это проблема с файловым дескриптором? Труба использует fd [0] - вход и fd [1] - выход. Может быть, fstream использует также тот же обработчик выходного файла?
Здесь «работает» образец: http://pastebin.com/gJ4PbHvy
#include <sys/types.h>
#include <cstdlib>
#include <unistd.h>
#include <iostream>
#include <fstream>
#define maxSize 64
using namespace std;
class Pipe
{
public:
Pipe()
{
pipe(fdesc);
}
~Pipe() {}
void writeBuffer(const char* message, size_t length)
{
close(fdesc[0]);
write(fdesc[1], message, length);
}
void readBuffer()
{
char buffer[maxSize];
close(fdesc[1]);
size_t result = read(fdesc[0], &buffer, sizeof(buffer));
cout << buffer << endl;
}
private:
int fdesc[2];
};
class Writer
{
public:
Writer(Pipe &obj)
{
pipe = obj;
}
~Writer()
{}
void entry()
{
std::string name = "./myFile";
ofstream file;
file.open(name.c_str(), ios::app);
std::string message = "hello world";
pipe.writeBuffer(message.c_str(), message.length()+1);
if (file.is_open())
{
file << "Hello World!" << endl;
file.close();
}
else
{
perror("file.is_open()");
}
sleep(1);
}
private:
Pipe pipe;
};
class Reader
{
public:
Reader(Pipe &obj)
{
pipe = obj;
}
~Reader()
{}
void entry()
{
pipe.readBuffer();
sleep(1);
}
private:
Pipe pipe;
};
int main(int argc, char *argv[])
{
Pipe pipe;
Reader reader(pipe);
Writer writer(pipe);
pid_t pid = fork();
if (pid == -1)
{
perror("fork");
exit(EXIT_FAILURE);
}
if (pid == 0)
{
// child process
while(1)
reader.entry();
}
else
{
// parent process
while(1)
writer.entry();
}
}
что somestream? Что такое сообщение? вопрос не имеет никакого смысла. – SergeyA
Вы можете рассмотреть это: файл << "anything"; и во втором примере вы не найдете «ничего» в созданном файле. Первый образец работает так, как ожидалось. – neutrino
Что такое 'ios :: app'? Вы проверяете, что файл был успешно открыт? Вы уверены, что файл закрыт, прежде чем проверять контекст файла? Между трубой и потоком, который вы используете, не может быть никакой связи. – SergeyA