【发布时间】:2016-03-13 21:52:08
【问题描述】:
我有一个管道来启用分叉程序中的两个进程之间的通信。它是通过 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)
在第二个例子中,“file
这是“工作”示例: 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?什么是消息?这个问题没有任何意义。
-
上下文太少,不使用水晶球无法回答。随机猜测:刷新文件。
-
什么是“someStream”?请创建一个SSCCE(最好在 ideone.com 之类的地方),并在此处发布整个 sscce。
-
@user4581301,不是句柄,而是描述符:)。老实说,我不确定如何让
std::ofstream对象与pipe调用返回的文件描述符共享相同的文件描述符 - 前提是您在包含 fstream 之前不调用使用#define private public 之类的重炮。 -
老鼠。朋友,那你什么也得不到。
标签: c++ linux pipe fork fstream