我做了两个线程,一个要读,另一个要写。但我有不确定的行为,有时我能读到1行,有时能读1000行。这对我来说没有多大意义。
我所做的如下: 1.我在main.cpp中用mkfifo()创建了一个先进先出2.我启动了两个线程,一个读,另一个写。reader.cpp,writer.cpp
在这些线程中,每个循环我打开fifo,然后关闭它,因为如果我只在循环之外做一次,它就不会工作,我也觉得很奇怪。
我一直在寻找好的例子,但一个也没有找到。
我的问题很简单,如何让fifo (读取器)等待传入的数据,并在数据可用时读取它。它应该能够以4 4Mhz的频率运行。
我希望有人能帮助我,因为这是我第三天在这件事上头破血流。如果有关系,我会使用Qt 4.8。
编辑:我找到了我的问题的解决方案:
main.cpp
#include <QtCore/QCoreApplication>
#include "reader.h"
#include "writer.h"
#include <sys/types.h> // mkfifo
#include <sys/stat.h> // mkfifo
#include <fcntl.h>
int main(int argc, char *argv[]) {
QCoreApplication a(argc, argv);
int fifo = mkfifo("/tmp/fifo", S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH);
Reader r;
Writer w;
r.start();
w.start();
return a.exec();
}
writer.h
#ifndef WRITER_H
#define WRITER_H
#include <QThread>
#include <stdio.h>
#include <iostream>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
class Writer : public QThread {
Q_OBJECT
public:
explicit Writer(QObject *parent = 0);
private:
void run();
};
#endif // WRITER_H
reader.h
#ifndef READER_H
#define READER_H
#include <QThread>
#include <stdio.h>
#include <iostream>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
class Reader : public QThread {
Q_OBJECT
public:
explicit Reader(QObject *parent = 0);
private:
void run();
};
#endif // READER_H
writer.cpp
#include "writer.h"
char * phrase = "Stuff this in your pipe and smoke it\n";
using namespace std;
Writer::Writer(QObject *parent) : QThread(parent) {}
void Writer::run() {
int num, fifo;
if ((fifo = open("/tmp/fifo", O_WRONLY)) < 0) {
printf("%s\n", strerror(errno));
return;
}
while (true) {
if ((num= write(fifo, phrase, strlen(phrase)+1)) < 0) {
printf("ERROR: %s\n", strerror(errno));
}
}
close(fifo);
}
reader.cpp
#include "reader.h"
using namespace std;
Reader::Reader(QObject *parent) : QThread(parent) {}
void Reader::run() {
int num, fifo;
char temp[38];
if ((fifo = open("/tmp/fifo", O_RDONLY)) < 0) {
printf("%s\n", strerror(errno));
return;
}
while (true) {
if ((num = read(fifo, temp, sizeof(temp))) < 0) {
printf("%s\n", strerror(errno));
}
printf("In FIFO is %d %s \n", num, temp);
}
close(fifo);
}
发布于 2012-09-25 20:06:53
基本的read()和write()函数并不保证读取或写入所有可用的数据。
你需要这样的东西:
int tot = 0;
while (tot < sizeof(temp))
{
num = read(fifo, temp + tot, sizeof(temp) - tot);
if (num < 0)
break;
tot += num;
}
对于write也一样。
发布于 2012-09-25 20:19:10
当周期性地打开和关闭单个管道时,我遇到了同样的问题。重新创建管道(在阅读器进程中,当满足EOF时)将是一种解决方案。
https://stackoverflow.com/questions/12582239
复制相似问题