命名管道linux

Named pipes linux

本文关键字:linux 管道      更新时间:2023-10-16

我做了两个线程,一个必须读取,另一个必须写入。但我有不明确的行为,有时我能读1行,有时读1000行。这对我来说没有多大意义。

我的工作如下:1.我在main.cpp中用mkfifo()创建了一个fifo2.我启动两个线程,一个读取,另一个写入。reader.cpp,writer.cpp

在这些线程中,每个循环我都打开fifo并关闭它,因为如果我只在循环外做一次,它就不会工作,我觉得这也很奇怪。

我一直在寻找好的例子,但没有找到。

我的问题很简单,我如何让fifo(阅读器)等待传入的数据,并在数据可用时读取它。它应该能够以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

阅读器.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 itn";
using namespace std;
Writer::Writer(QObject *parent) : QThread(parent) {}
void Writer::run() {
int num, fifo;
if ((fifo = open("/tmp/fifo", O_WRONLY)) < 0) {
printf("%sn", strerror(errno));
return;
}
while (true) {
if ((num= write(fifo, phrase, strlen(phrase)+1)) < 0) {
printf("ERROR: %sn", 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("%sn", strerror(errno));
return;
}
while (true) {
if ((num = read(fifo, temp, sizeof(temp))) < 0) {
printf("%sn", strerror(errno));
}
printf("In FIFO is %d %s n", num, temp);
}
close(fifo);
}

基本的read()和write()函数不承诺读取或写入所有可用数据。

你需要这样的东西:

int tot = 0;
while (tot < sizeof(temp))
{
num = read(fifo, temp + tot, sizeof(temp) - tot);
if (num < 0)
break;
tot += num;
}

写作也是如此。

我在定期打开和关闭单个管道时遇到了同样的问题。重新创建管道(在读取器过程中,当满足EOF时)将是一个解决方案。