命名管道linux
Named pipes linux
我做了两个线程,一个必须读取,另一个必须写入。但我有不明确的行为,有时我能读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时)将是一个解决方案。
相关文章:
- 在 Azure DevOps 构建管道中使用英特尔C++编译器为 Linux 环境构建C++代码
- GSTREAMER管道播放,但没有填充的回调(仅在Android上发生,在Windows和Linux上可行)
- 如何在 Linux C++ 应用程序中通过管道传输到 ifstream
- 递归执行C 中的Linux管道命令
- 为什么这里的程序体现在Linux中命名的管道的使用情况会遭受种族条件
- 从 Linux 中的多个非阻塞命名管道读取
- 命名管道linux
- Linux 标准输出管道问题
- 无法使用 istream 和 ostream 指针跨 Linux 管道写入
- 在 Linux C++的两个线程之间使用管道的错误/意外行为
- 从 Linux 中的管道/套接字读取所有结构或什么都没有
- 无法写入 Linux 中的管道
- 为什么Linux中的管道会丢失空间
- 每次我在linux c++中为命名管道运行程序时,都会发出SIGSTOP信号
- 在linux中使用命名管道的简单客户端/服务器程序
- 数据报管道在Linux中可能吗?
- 命名管道在c++ Linux检查缓冲区是否已满
- 为什么linux管道和标准输出不能一起工作
- c++: Linux:管道到我的程序从多个线程或流,而不是' cout '
- Open()、Close()和Read()应用于Linux管道文件描述符