命名管道linux

时间:2012-09-25 11:43:17

标签: c++ qt named-pipes

我做了2个线程,一个必须读另一个必须写。 但是我得到了未定义的行为,有时我可以读1行,有时1000行。这对我来说没有多大意义。

我所做的是以下内容: 1.我在main.cpp中创建了一个带有mkfifo()的fifo 2.我开始2个线程,一个读取,另一个写入。 reader.cpp,writer.cpp

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

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

我的问题很简单,如何使fifo(Reader)等待传入数据并在可用时读取它。它应该能够以4Mhz运行。

我希望有人可以帮助我,因为这是第3天我对此表示不满。如果我使用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);
}

2 个答案:

答案 0 :(得分:3)

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

您需要以下内容:

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

写作也一样。

答案 1 :(得分:1)

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

相关问题